在struct和vec复合型数据类型中,struct和vec 默认是拥有变量的所有权的。如下代码:
fn main() {
let a = Box::new(1);
let b = Box::new(2);
let c = Point { x: a, y: b };
// let d = vec![a, b];
println!("{:?}", b);
println!("{:?}", a);
// println!("{:?}", d);
}
#[derive(Debug)]
struct Point {
x: Box<i32>,
y: Box<i32>,
}
提示如下错误:
--> src\main.rs:5:9
|
5 | let c = Point { x: a, y: b };
| ^ help: if this is intentional, prefix it with an underscore: `_c`
|
= note: `#[warn(unused_variables)]` on by defaulterror[E0382]: borrow of moved value: `b`
--> src\main.rs:7:22
|
3 | let b = Box::new(2);
| - move occurs because `b` has type `Box<i32>`, which does not implement the `Copy` trait
4 |
5 | let c = Point { x: a, y: b };
| - value moved here
6 | // let d = vec![a, b];
7 | println!("{:?}", b);
| ^ value borrowed here after moveerror[E0382]: borrow of moved value: `a`
--> src\main.rs:8:22
|
2 | let a = Box::new(1);
| - move occurs because `a` has type `Box<i32>`, which does not implement the `Copy` trait
...
5 | let c = Point { x: a, y: b };
| - value moved here
...
8 | println!("{:?}", a);
| ^ value borrowed here after moveerror: aborting due to 2 previous errors; 1 warning emitted
For more information about this error, try `rustc --explain E0382`.
error: could not compile `pointer`