使用字段的可变引用的更改不会在移动原始实例后反映出来

Changes using mutable reference of a field are not reflected after move of the original instance

我试图通过从其实例 foo.

借用可变引用来操作结构 Foo 的字段 x

如果我尝试使用实例 foo 的移动绑定 y 打印字段 x 原始移动之后例如,它一直打印未更改的值。

下面的简化示例:

struct Foo {
    x: i32,
}

fn main() {
    let mut foo = Foo { x: 42 };
    let x = &mut foo.x;
    *x = 13;
    let y = foo;
    println!("{}", y.x); // -> 42; expected result: 13
}

相反,如果我打印移动的绑定 y 本身,它会打印更改后的值。

println!("{:?}", y); // -> Foo { x: 13 }

或者,如果我在 移动之前打印 xfoo.x 之类的其他内容,它会按预期打印内容。

println!("{}", x); // -> 13
let y = foo;
println!("{}", y.x); // -> 13

这是有意为之的行为吗?

这是编译器中的一个已知错误,仅影响 rustc 1.45。 rustc 1.44 不受影响,该问题已在 Beta 版上修复,这意味着它将在 rustc 1.46 上修复。

一个问题has been opened 跟踪它。

虽然这个问题看起来很严重,但根据 oli-obk,rustc 的主要贡献者之一,特别是在 const 表达式上,它不太可能在实际代码中被发现:

The bug is almost impossible to trigger on real world code. You need all values that are going into the bug to be constant values and there can't be any control flow or function calls in between.

版本 1.45.1 has been released and contains a backport of the fix from beta, among other things. Later version 1.45.2 已发布,其中包含更多(不相关的)修复。