Any safe way to transmute Vec<Option<&Foo>> to Vec<&Foo>?

62 points Linguistic-mystic

I’m thinking about the advantages that Rust’s single mutable aliasing rule gives, and I think safe type transmutation is a big one. But it somehow doesn’t get emphasized.

Let’s say we have a &mut Vec<Option<&Foo>>. That means there are no other references to that vector, anywhere. And if we inspect the values inside and see there are no Nones, then what we really have is a vector of non-null references. And since Option references are transparently represented, we can just tighten the type without changing any data in memory! Now, I know about std::mem::transmute but that is unsafe hackery. Is there any safe built-in cast in Rust for that?

It could also be used for other kinds of type refinement: validate that a vector of integers is a vector of non-zero integers, validate that a vector of floating-points contains no NaNs and so on. This is all possible due to Rust’s aliasing rules (which even Haskell doesn’t have) and so I think should be capitalized on.