Closure move 数值类型与引用类型的区别

在使用 闭包+move后 数值类型的变量仍然可以引用,但是string变量不能再引用,提示已经“value borrowed here after move”,从这里可以引申,其它引用类型如struct 应该跟string一样处理。
pub fn main(){
    let ch='英';
    let  ch2=& ch;
    let  ch3=& ch;
    println!("{:?}",(&ch,ch2,ch3));

    let  ch=String::from("英");
    let  ch2=&ch;
    let ch3=& ch;
    println!("{:?}",(&ch,ch2,ch3));

    let mut b = false;
    let x = &mut b;    
    {
        let mut c = || { *x = true; };
        // The following line is an error:
        // let y = &x;
        c();
        println!("{:?}",x);
    }    
    let z = &x;
    //b=true;
    println!("{:?}",z);

    let mut num = 5;    
    let add_num = || println!("Closure   num:{:?}",num);
    add_num();
    let a=&mut num;
    println!("num:{:?}",&num);

    let mut add_num = || {num+=5;println!("Closure   num:{:?}",&num);};
    add_num();
    println!("num:{:?}",&num);
    let a=&mut num;
    println!("num:{:?}",a);

    let mut add_num = move ||{num+=5;println!("Closure   num:{:?}",&num);};
    add_num();
    println!("num:{:?}",&num);
    let a=&mut num;
    println!("num:{:?}",a);


    let mut num = String::from("hello");    
    let add_num = || println!("Closure   num:{:?}",num);
    add_num();
    let a=&mut num;
    println!("num:{:?}",&num);

    let mut add_num = || {num+="5";println!("Closure   num:{:?}",&num);};
    add_num();
    println!("num:{:?}",&num);
    let a=&mut num;
    println!("num:{:?}",a);

    
    let mut add_num = move || {num+="5";println!("Closure   num:{:?}",&num);};
    add_num();
    //let a=&mut num; // ^^^^^^^^ value borrowed here after move
    //println!("num:{:?}",a);   
}

猜你喜欢

转载自www.cnblogs.com/liufu627/p/12571881.html