[][src]Function tao_of_rust::ch05::semantic::ownership_change

pub fn ownership_change()

所有权是否转移

Base usage: 结构体默认没有实现Copy

#[derive(Debug)]
struct A{
    a: i32,
    b: u32,
}
fn main(){
    let a = A {a: 1, b: 2};
    let b = a;  // a的所有权会转移
    println!("{:?}", a);
}Run

Base usage: 手工为结构体实现Copy

#[derive(Debug, Copy, Clone)]
struct A{
    a: i32,
    b: u32,
}
fn main(){
    let a = A {a: 1, b: 2};
    let b = a;  // a的所有权没有转移,因为这里是复制语义
    println!("{:?}", a);
}Run

Base usage: 元组默认实现Copy

fn main(){
    let a = ("a".to_string(), "b".to_string());
    let b = a;  // String是移动语义,所以此处a会移动
    // println!("{:?}", a);
    let c = (1,2,3); // 此处为复制语义
    let d = c;
    println!("{:?}", c);
}Run