这里有一个关于Rust's move语义的很好的例子:Rust By example网站上的Rust Move Semantics.
我对这两个 case 都有基本的了解.第一个问题是,原语可以有一个新的别名,而原语仍然可以使用,因为最终的结果是一个副本,因为i32
利用了Copy
特征.这对我来说很有意义.
此外,出于许多好的原因,第二个示例在具有多个别名(表示堆上的i32
)方面是有意义的.Rust强制执行所有权规则,因此,既然创建了新绑定,就不能使用原始别名.这有助于防止数据竞争、双重释放等.
但似乎还有第三个 case 没有被提及.How does Rust implement moves of stack allocated structs that do not implement the 100 trait?以下代码说明了这一点:
#[derive(Debug)]
struct Employee{
age: i32,
}
fn do_something(m: Employee){
println!("{:?}", m);
}
fn main() {
let x = Employee {
age: 25,
};
do_something(x);
//compiler error below because x has moved
do_something(x);
}
我知道:在上面的例子中,Rust will allocate the 100 on the stack.上述 struct does not implement the 101 trait,因此在分配给新别名时不会被复制.这让我非常困惑,因为如果在堆栈上分配了Employee
struct ,并且没有实现Copy
trait,那么它在哪里/如何移动?它是否实际移动到do_something()
的堆栈帧?
在解释这一难题时,任何帮助都将不胜感激.