我的C++背景让我对内部可变性感到不舒服。
从借用检查器的角度来看,处理每个结构体上的许多引用,这些引用的内部状态可能很快或很久以后会被改变,是不可能的;这显然就是内部可变性可以发挥作用的地方。
此外,在《Rust编程语言》的第15.5章“RefCell和内部可变性模式”中,关于Messenger
特质及其在MockMessenger
结构上的实现的示例使我想到,即使很明显某种可变性迟早会成为必需,也通常会系统地优先选择&self
而不是&mut self
。
当发送消息时,Messenger
的实现如何不改变其内部状态呢?异常情况只是打印消息,这与&self
一致,但一般情况可能包括写入某种内部流,这可能涉及缓冲、更新错误标志等等,所有这些都肯定需要&mut self
,例如impl Write for File
。
依赖内部可变性来解决这个问题对我来说听起来像是在C++中使用const_cast
或滥用mutable
成员,只是因为我们在应用程序的其他地方没有保持一致性(这是C++学习者常犯的错误)。
因此,回到下面的示例代码,我应该:
- 从
change_e()
到change_i()
使用&mut self
(即使不是必须的,编译器也不会抱怨),以保持与存储的整数值被更改的事实一致? - 继续使用
&self
,因为内部可变性允许它,即使我实际上改变了存储的整数值?
这个决定不仅局限于结构体本身,而且将对使用这个结构体的应用程序表达能力产生很大影响。第二种解决方案肯定会有很大帮助,因为只涉及共享引用,但它是否符合Rust的期望呢?
我在Rust API Guidelines中找不到这个问题的答案。是否有其他类似于C++ Core Guidelines的Rust文档?
/*
$ rustc int_mut.rs && ./int_mut
initial: 1 2 3 4 5 6 7 8 9
change_a: 11 2 3 4 5 6 7 8 9
change_b: 11 22 3 4 5 6 7 8 9
change_c: 11 22 33 4 5 6 7 8 9
change_d: 11 22 33 44 5 6 7 8 9
change_e: 11 22 33 44 55 6 7 8 9
change_f: 11 22 33 44 55 66 7 8 9
change_g: 11 22 33 44 55 66 77 8 9
change_h: 11 22 33 44 55 66 77 88 9
change_i: 11 22 33 44 55 66 77 88 99
*/
struct Thing {
a: i32,
b: std::boxed::Box<i32>,
c: std::rc::Rc<i32>,
d: std::sync::Arc<i32>,
e: std::sync::Mutex<i32>,
f: std::sync::RwLock<i32>,
g: std::cell::UnsafeCell<i32>,
h: std::cell::Cell<i32>,
i: std::cell::RefCell<i32>,
}
impl Thing {
fn new() -> Self {
Self {
a: 1,
b: std::boxed::Box::new(2),
c: std::rc::Rc::new(3),
d: std::sync::Arc::new(4),
e: std::sync::Mutex::new(5),
f: std::sync::RwLock::new(6),
g: std::cell::UnsafeCell::new(7),
h: std::cell::Cell::new(8),
i: std::cell::RefCell::new(9),
}
}
fn show(&self) -> String // & is enough (read-only)
{
format!(
"{:3} {:3} {:3} {:3} {:3} {:3} {:3} {:3} {:3}",
self.a,
self.b,
self.c,
self.d,
self.e.lock().unwrap(),
self.f.read().unwrap(),
unsafe { *self.g.get() },
self.h.get(),
self.i.borrow(),
)
}
fn change_a(&mut self) // &mut is mandatory
{
let target = &mut self.a;
*target += 10;
}
fn change_b(&mut self) // &mut is mandatory
{
let target = self.b.as_mut();
*target += 20;
}
fn change_c(&mut self) // &mut is mandatory
{
let target = std::rc::Rc::get_mut(&mut self.c).unwrap();
*target += 30;
}
fn change_d(&mut self) // &mut is mandatory
{
let target = std::sync::Arc::get_mut(&mut self.d).unwrap();
*target += 40;
}
fn change_e(&self) // !!! no &mut here !!!
{
// With C++, a std::mutex protecting a separate integer (e)
// would have been used as two data members of the structure.
// As our intent is to alter the integer (e), and because
// std::mutex::lock() is _NOT_ const (but it's an internal
// that could have been hidden behind the mutable keyword),
// this member function would _NOT_ be const in C++.
// But here, &self (equivalent of a const member function)
// is accepted although we actually change the internal
// state of the structure (the protected integer).
let mut target = self.e.lock().unwrap();
*target += 50;
}
fn change_f(&self) // !!! no &mut here !!!
{
// actually alters the integer (as with e)
let mut target = self.f.write().unwrap();
*target += 60;
}
fn change_g(&self) // !!! no &mut here !!!
{
// actually alters the integer (as with e, f)
let target = self.g.get();
unsafe { *target += 70 };
}
fn change_h(&self) // !!! no &mut here !!!
{
// actually alters the integer (as with e, f, g)
self.h.set(self.h.get() + 80);
}
fn change_i(&self) // !!! no &mut here !!!
{
// actually alters the integer (as with e, f, g, h)
let mut target = self.i.borrow_mut();
*target += 90;
}
}
fn main() {
let mut t = Thing::new();
println!(" initial: {}", t.show());
t.change_a();
println!("change_a: {}", t.show());
t.change_b();
println!("change_b: {}", t.show());
t.change_c();
println!("change_c: {}", t.show());
t.change_d();
println!("change_d: {}", t.show());
t.change_e();
println!("change_e: {}", t.show());
t.change_f();
println!("change_f: {}", t.show());
t.change_g();
println!("change_g: {}", t.show());
t.change_h();
println!("change_h: {}", t.show());
t.change_i();
println!("change_i: {}", t.show());
}
Messenger
trait示例是误导性的?设计这样的trait意味着强制实现依赖内部可变性。 - prog-fhWrite
特质确实使用了&mut self
,但是File
本身实际上并没有。您可以通过使用&'_ File
的实现 来向&File
写入和读取数据。(这不涉及内部可变性;这只是底层操作系统 API 的工作方式。) - trent