Moving in and out of a volatile borrowed structure

Can someone explain why the transfer of values ​​to borrowed structures is valid when moving them? For instance:

struct S { v: Vec<u8> } fn move_v_out(s: &mut S) { let old_vecotr = sv; // If removed, program compiles fine sv = vec![]; } fn main() { let mut v = S { v: vec![] }; move_v_out(&mut v); } 

In any case, a member of a mutually borrowed structure changes. However, a compilation error occurs.

+6
source share
1 answer

The main difference is that when you move a value from a borrowed structure, you leave it in a "partially moved state", which subsequently prohibits its use as a whole structure.

And this state is forbidden for borrowed values, since they must remain valid at the end of the function, and the compiler does not (yet?) Understand that after that you set the value correctly.

However, if you want to do this, remove the old Vec and replace it with a new one, the standard library contains the function you need: std::mem::replace

 fn move_v_out(s: &mut S) { let old_vector = std::mem::replace(&mut sv, vec![]); // do something with old_vector } 
+9
source

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


All Articles