Rust学习笔记(3)——struct/vec的所有权

本文通过一个具体的Rust代码示例,详细解释了Rust语言中struct和vec复合型数据类型的变量所有权转移及借用规则,揭示了在使用这些复合类型时如何避免常见的错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在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 default

error[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 move

error[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 move

error: aborting due to 2 previous errors; 1 warning emitted

For more information about this error, try `rustc --explain E0382`.
error: could not compile `pointer`

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值