Is my understanding correct that in Rust it is not possible to protect reference members of a struct from modification while having the reference target values mutable? (Without runtime borrow checking that is.) For example:
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;
}
Not being able to change the reference value may be useful in certain FFI situations. FFI and the performance requirements reasons prevent the use of runtime borrow checking here.
In C++ it can be expressed like this:
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
}
MyDatastruct and then loads two dynamic libraries. It gives these 2 dynamic libs pointers to the allocatedMyDataand allows the libs to access and change the value pointed at by thesome_reffield (it takes care of ensuring they don't do it at the same time), but it must prevent them from changing thesome_refreference itself, because for its own reasons it must ensure that the data is located at that specific address where it allocated it. I bet one can come up with an example that does not involve dylibs too./proc/memand friends). If you just want to protect again accidental misuse, this is another story.constaway and assign to the reference.