Mutable borrow from immutable input(s)

what is the problem with Clippy on if we return mutable from immutable . see the the following code…

pub unsafe fn get_unchecked_mut(&self, key: usize) -> &mut T {

self.get_element_at(key).get_occupied_mut()

}

I means above code is working properly , but clippy suggesting us its as error (https://rust-lang.github.io/rust-clippy/master/index.html#mut_from_ref)

Simply stated, this is an UB if you somehow transform immutable reference to a variable into mutable one. Clippy doesn’t try to look at the function’s body to determine whether it is the case or two references are unrelated, it just throws a warning in. And, so to say, your code in fact contains an UB: if some optimisation assumes that the object is immutable, but it was in fact mutated (through the reference acquired by this function), you’ll easily can get anything wrong.

1 Like

Even if you are using interior mutability, this is almost always UB.
Note: The only way to use interior mutability is by using UnsafeCell or types that use UnsafeCell, like Cell, Mutex, or Atomic*.

1 Like

thanks for your reply… its means rust compiler allow UB… if yes, in this case, compiler , at least , must warn us.

If we use UnsafeCell , there is also get function of UnsafeCell (https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html), which doing the same thing… So, what is the difference between doing manually or using UnsafeCell.

UnsafeCell is treated specially (more about it and the similar cases here). It is marked as the only thing which can be modified while being behind shared reference.

3 Likes

When you use unsafe {}, you take responsibility for ensuring the safety rules are upheld, as otherwise the unsafety can spread beyond the block.

1 Like

UnsafeCell is a language item. It is allowed to be modified under shared reference in the same sense as ManuallyDrop will not run destructor of its content.

Unsafe Rust is much more unsafe than unsafe C/++ as Rust restricts far much more things for the sake of performance. Those restrictions are automatically proven by compiler in safe context. But in unsafe { } it is you who has responsibility to guarantee ALL those restrictions. That’s why I always (half-seriously) shout that the unsafe keyword should be renamed to unsafe_but_trust_me_i_know_what_im_doing_here

1 Like

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.