Skip to main content

rust 所有权

背景

所有权

move

rust 是move 语义的

fn main(){
let x = String::from("hello");
let y = x; // 这个时候 , x 已经失去了1 的所有权
let z = x;
}

会有错误

let z = x;
| ^ value used here after move

copy

fn main(){
let x = 1;
let y = x; // 这个时候 , x 没有失去所有权 ,为什么呢? , 因为copy trait
let z = x;
}

copy vs move

来源
assignment operate

Types whose values can be duplicated simply by copying bits.

By default, variable bindings have ‘move semantics.’ In other words:

#[derive(Debug)]
struct Foo;

let x = Foo;

let y = x;

// `x` has moved into `y`, and so cannot be used

// println!("{x:?}"); // error: use of moved value

However, if a type implements Copy, it instead has ‘copy semantics’:

// We can derive a Copy implementation. Clone is also required, as it's // a supertrait of Copy.

#[derive(Debug, Copy, Clone)]
struct Foo;

let x = Foo;

let y = x;

// `y` is a copy of `x`

println!("{x:?}"); // A-OK!

It’s important to note that in these two examples, the only difference is whether you are allowed to access x after the assignment. Under the hood, both a copy and a move can result in bits being copied in memory, although this is sometimes optimized away.

assignment operator

ref from

Moved and copied types
When a place expression is evaluated in a value expression context, or is bound by value in a pattern, it denotes the value held in that memory location. If the type of that value implements Copy, then the value will be copied. In the remaining situations, if that type is Sized, then it may be possible to move the value. Only the following place expressions may be moved out of:
Variables which are not currently borrowed.
Temporary values.
Fields of a place expression which can be moved out of and don't implement Drop.
The result of dereferencing an expression with type Box<T> and that can also be moved out of.
After moving out of a place expression that evaluates to a local variable, the location is deinitialized and cannot be read from again until it is reinitialized. In all other cases, trying to use a place expression in a value expression context is an error.

相关阅读