*const T to *mut T?

Is it possible to cast *const T to *mut T and vice versa?
What happens internally

If it happens then why 2 types.

Yes you can cast between them. The only difference is that *const T is covariant with respect to T and *mut T is invariant with respect to T.

Yes, the differences are:

  1. Methods in std usually take one or the other. This works as a lint and helps writing correct code.
  2. They differ in variance.

Safety-wise, it is not the kind of pointer that determines whether it is safe to mutate through the raw pointer. Rather, it is whether you originally got the raw pointer from an immutable reference that determines it.

7 Likes

@alice out of curiosity, is this stuff documented anywhere? I couldn't find anything germane in the language reference, the 'nomicon, or the std docs.

Well, poorly. You should be able to find some info in the stacked borrows post.

That is the main author of miri's blog, and many of the other posts are relevant as well.

2 Likes

The Unsafe Code Guidelines working group will be writing the official documentation about this, once the exact semantics are worked out.

1 Like