我的理解是否正确:在Rust中,当引用结构体的成员时,不可能保护它们不被修改而又让引用目标值可变?(没有运行时借用检查的情况下)例如:
struct MyData<'a> {
pub some_ref: &'a mut i32,
}
fn doit<'a>(data: &mut MyData<'a>, other_ref: &'a mut i32) {
// I want to be able to do the following here:
*data.some_ref = 22;
// but make it impossible to do the following:
data.some_ref = other_ref;
}
在某些FFI情况下,不能更改引用值可能是有用的。FFI和性能要求的原因阻止了在此处使用运行时借用检查。
在C++中,可以这样表达:
struct MyData {
int* const some_ref;
};
void doit(const MyData &data, int* other_ref) {
// this is allowed:
*data.some_ref = 22;
// this is not:
data.some_ref = other_ref; // compile error
}
MyData
结构体,然后加载了两个动态库。它将这两个动态库的指针给予已分配的MyData
,并允许库访问和更改由some_ref
字段指向的值(它确保它们不会同时进行更改),但必须防止它们更改some_ref
引用本身,因为出于自己的原因,它必须确保数据位于分配它的特定地址上。我敢打赌,你可以想出一个不涉及dylibs的例子。 - Lev Himmelfarbconst
并分配给引用。 - Chayim Friedman