let mut op = Some(100);
match op {
None => {}
Some(ref mut x) => {
let mut change = x;
*change += 1000;
println!("{:?}",*change);
}
}
println!("{:?}",op);
改为这样,输出为
1100
Some(1100)
现在让我们测试一下是否发生了拷贝
struct Data {
dat: i32
}
impl std::clone::Clone for Data {
fn clone(&self) -> Data{
println!("object cloned");
Data {dat: self.dat}
}
}
impl std::fmt::Debug for Data {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{:?}", self.dat)
}
}
fn main() {
let mut op = Some(Data {dat: 100});
match op {
None => {}
Some(mut x) => {
let mut change = &mut x;
(*change).dat += 1000;
println!("{:?}",change);
}
}
println!("{:?}",op);
}
编译,出现错误
error[E0382]: use of partially moved value: `op`
--> src\main.rs:28:21
|
22 | Some(mut x) => {
| ----- value moved here
...
28 | println!("{:?}",op);
| ^^ value used here after move
|
= note: move occurs because the value has type `Data`, which does not implement the `Copy` trait
可以看到,match获得了op的所有权,因此op失效。而作为i32类型,op是不会失效的,因此发生了一次复制
而利用ref获得的是原变量的指针,因此不会发生所有权转移