【问题标题】:Why can a variable be bound to another value even its ownership has moved? [duplicate]为什么一个变量可以绑定到另一个值,即使它的所有权已经移动了? [复制]
【发布时间】:2023-03-22 21:47:01
【问题描述】:

在下面的代码中,MyStruct { s: 5u32 } 的所有权被let y = x; 移动到了y,但是为什么x.s = 6 仍然有效?

struct MyStruct {
    s: u32,
}

fn main() {
    let mut x = MyStruct { s: 5u32 };
    let y = x;
    x.s = 6; //why this line does not cause an error?
    println!("{}", y.s);
}

【问题讨论】:

    标签: rust


    【解决方案1】:

    我很确定这是一个错误,因为在末尾添加行 println!("{}", x.s) 会导致编译器报错。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-07
      • 1970-01-01
      • 2017-10-12
      • 2016-08-14
      • 2012-11-25
      • 1970-01-01
      • 2017-04-11
      • 1970-01-01
      相关资源
      最近更新 更多