Re:Why Rust helps even if you have to use a lot of `unsafe`
by ReactiveJelly on Wednesday August 02, 2023 @11:56AM
(#36972648)
> I don't know if such shape-shifting is allowed in Rust
I think so! You mean this?
let mut x: Result <bool, String> = Ok (false);
dbg! (&x);
// Get a reference to the bool and mutate it
if let Ok (b) = &mut x {
*b = true;
}
dbg! (&x);
// "shape-shift" to the other enum variant
x = Err ("No boolean :(".to_string ());
dbg! (&x);
It runs in Godbolt https://godbolt.org/z/q6jqYdYh1
Sum types are also quite nice to bridge the gap from a 'dynamically typed mindset' into a 'statically typed mindset'. Sum types basically provide the ability that a variable can assume different types during its lifetime (? although I don't know if such 'shape-shifting' is allowed in Rust), so it almost feels like Python or Javascript, but since the compiler 'knows' sum types it's all still completely typesafe.
In Typescript it's convenient and frankly quite nice, in a programming language like Rust where performance matters I'd be less enthusiastic though.