4 ms·
That's helpful for that one example, but it doesn't solve the general case. I can think of a hundred different examples that aren't handled by the type system o
by game-of-throws 4y ago
That's helpful for that one example, but it doesn't solve the general case. I can think of a hundred different examples that aren't handled by the type system or stdlib.
fn high_word(n: u32) -> u16 {
(n >> 16).try_into().unwrap()
}
Unless someone manages to solve the halting problem, we'll always need unwrap() or equivalent.
- forrestthewoods 4y agoMaybe the function unwrap should be renamed to ISolemnlySwearThisCanNeverFail.
- proto_lambda 4y agoWe'd need an even more unholy name for `unsafe { foo.unwrap_unchecked() }`!
- forrestthewoods 4y agoThat’s a feature! I’d be thrilled if C++ required wrapping declaration and use of global variables with ‘unsafe_and_evil { … }’
- andrewaylett 4y agoIt's also the case that this call to `unwrap()` will be removed by dead code elimination. See: https://play.rust-lang.org/?version=nightly&mode=release&edition=2021&gist=7ec24a5649a45b964d507434e499256c https://play.rust-lang.org/?version=nightly&mode=release&edi... Where if you look at the asm for playground::high_word then you'll see it's a bare shrl. I'd quite like an analogue to unwrap() that's checked at compile time -- an out for the type checker, but an error if it's not dead code eliminated. This helps us to trust and rely on the compiler, and is the converse of `unsafe_unwrap`, which tells the compiler to trust us.
- bombela 4y agoIn this example you could do: (n >> 16) as u16 There is also this thing called "Infallible". Which will eventually be merged with "!". To express to the compiler and the programmer that something can never fail. https://doc.rust-lang.org/std/convert/enum.Infallible.html https://doc.rust-lang.org/std/convert/enum.Infallible.html