【发布时间】:2018-05-01 22:24:17
【问题描述】:
如果我有一个绑定到结构的不可变变量,Rust 通常不允许我改变结构的字段或拥有的子结构的字段。
但是,如果该字段是可变引用,Rust将允许我改变引用的对象,尽管我的绑定是不可变的。
为什么允许这样做?是不是不符合 Rust 的正常不变性规则?
Rust 不会让我通过不可变引用来做同样的事情,因此不可变引用与不可变绑定具有不同的行为。
代码示例:
struct Bar {
val: i32,
}
struct Foo<'a> {
val: i32,
bar: Bar,
val_ref: &'a mut i32,
}
fn main() {
let mut x = 5;
{
let foo = Foo {
val: 6,
bar: Bar { val: 15 },
val_ref: &mut x
};
// This is illegal because binding is immutable
// foo.val = 7;
// Also illegal to mutate child structures
// foo.bar.val = 20;
// This is fine though... Why?
*foo.val_ref = 10;
let foo_ref = &foo;
// Also illegal to mutate through an immutable reference
//*foo_ref.val_ref = 10;
}
println!("{}", x);
}
【问题讨论】:
-
@Shepmaster 确实那篇文章是相似的——尽管我的问题更关注为什么
*foo.val_ref = 10;是可以接受的,而不是为什么其他人不能接受。从我的 POV 来看,我的示例中的所有内容似乎都不应该通过不可变绑定来接受。
标签: rust