What happens when you use multiple nested areas?

fn main() {
    let mut m = 12;
    {
        let n = &mut m;
        *n = 13;
        {
            let k = n;
            *k = 20;
            println!("{}", k);
        } // k scope ends here, right?
        println!("{}", n);
    }
    println!("{}", m);
}

Here is what I got when I ran the code:

src/main.rs:11:18: 11:19 error: use of moved value: `n` [E0382]
src/main.rs:11      println!("{}", n);
                               ^

But hasn't the variable kfinished its field yet? Why wasn't ownership of the variable returned n?

+4
source share
1 answer

But has the variable k not yet exhausted its area? Why did he not give property back to variable n?

Yes, the area is kover, but why do you think it should return ownership?

Rust " ". Copy ( &mut ), . , , . , k , "" ( , ). n, , .

&mut , , , , &mut *p . , ( , , , , - ), . , :

fn main() {
    let mut m = 12;
    {
        let n = &mut m;
        *n = 13;
        {
            let k = &mut *n;  // explicit referencing of the dereferenced value
            *k = 20;
            println!("{}", k);
        }
        println!("{}", n);
     }
     println!("{}", m);
}

, , n k k.

, ( Veedrac ) - :

fn main() {
    let mut m = 12;
    {
        let n = &mut m;
        *n = 13;
        {
            let k: &mut _ = n;  // automatic reborrowing because of type annotation
            *k = 20;
            println!("{}", k);
        }
        println!("{}", n);
     }
     println!("{}", m);
}

, , , , , (, ), , . , .

+8

Source: https://habr.com/ru/post/1614618/


All Articles