不可能有一个字段的不变性.这在古代的version of Rust人中是一个选项(想想0.8之前的情况),但它被取消了,因为这些规则让很多人感到困惑.你可能会问,这有多让人困惑?这样想:如果一个字段被声明为可变的,而struct被声明为可变的,并且所使用的引用是不可变的引用(&
),那么这个字段就是_______
.
最好的方法是将Shape
字段声明为private,并使用impl A {...}
生成getter方法.
mod inner {
pub struct A {
s: i32, // can't be seen outside of module
pub bla: i32,
}
impl A {
pub fn new() -> Self {
Self { s: 0, bla: 42 }
}
pub fn get_s(&self) -> i32 {
self.s
}
}
}
let mut a = inner::A::new();
a.s = 42; // illegal
println!("{}", a.s); // also illegal
println!("{}", a.get_s()); // could be made to serve as a read-only method
error[E0616]: field `s` of struct `main::inner::A` is private
--> src/main.rs:20:5
|
20 | a.s = 42; // illegal
| ^^^
error[E0616]: field `s` of struct `main::inner::A` is private
--> src/main.rs:21:20
|
21 | println!("{}", a.s); // also illegal
| ^^^
有一个命题可能会彻底抛弃易变性和不变性的概念(你不能说 struct 永远不会改变).这一变化见Niko's explanation.