[][src]Function tao_of_rust::ch05::smart_pointer::box_demo

pub fn box_demo()

智能指针和所有权: Box

Base usage: Box独占所有权

fn main(){
    let x = Box::new("hello");
    let y = x;
    // error[E0382]: use of moved value: `x`
    // println!("{:?}", x);
}Run

Base usage: Box可以使用解引用,并且支持解引用移动所有权操作

fn main(){
    let a = Box::new("hello");
    let b = Box::new("Rust".to_string());
    let c = *a;
    let d = *b;
    println!("{:?}", a);
    // error[E0382]: use of moved value: `b`
    // println!("{:?}", b);
}Run

Base usage: Rc和Arc不支持解引用移动

use std::rc::Rc;
use std::sync::Arc;
fn main(){
    let r = Rc::new("Rust".to_string());
    let a = Arc::new(vec![1.0, 2.0, 3.0]);
    // error[E0507]: cannot move out of borrowed content
    // let x = *r;
    // println!("{:?}", r);
    // error[E0507]: cannot move out of borrowed content
   // let f = *foo;
}Run