by dietrichepp · 4y ago · 0 comments
The basic argument is something like "all functions should be total", but the problem is that proving that a function is total is really annoying, so we live with two other consequences instead:
1. Some functions are not total, and you just have to know the preconditions.
2. Some functions are total, but the type system is not powerful enough to prove this (possibly because they call functions in category #1).
The same discussion has been going on for decades in Haskell-land, and there's no definitive consensus, but my sense is that we'd rather tolerate a panic here and there rather than try and deal with the fuss of propagating errors or proving that our functions are total in the first place. For example, take a look at this function. I ask,
> Is this a reasonable way to write this?
struct IVec2(i32, i32);
impl IVec2 {
fn parse(d: [u8; 8]) -> Self {
Vec2(i32::from_le_bytes(d[0..4].try_into().unwrap()),
i32::from_le_bytes(d[4..8].try_into().unwrap()))
}
}
Someone from the Rust community will come in and say,> Arguably, unwrap() is unreasonable.
...but why? The function is total. It won't panic. The response is,
> ... an error should be properly handled ...
There is no error, the code can't fail. I don't know of another way to write the function without a panic hidden somewhere, either in an unwrap() or inside an indexing operation. For some reason, some members of the Rust community think of this as a problem to be solved.
It's not a problem. The unwrap() method is just too damn useful. It's too damn useful to be able to write functions that are not total. I'd say that the key here is coming up with a sensible style for when you are okay with panicking in your code, and then accepting the consequences of that decision.
("Total" means that the function returns a result for all inputs. Unwrap is not total. In Haskell, "head" is not total--it returns the first element of a list, but throws an exception if the list is empty.)
I recently had a nontrivial project where I'd used maybe a dozen unwrap()s in different places and had gotten a handful of bug reports for resulting panics. So I decided to make a pass and finally clean them up
Project-wide search for unwrap(), went through and properly handled all of them, very quickly and easily plugged all the holes, no more panics being reported
split_array will eventually allow something like the following, which avoids any explicit indexing and will fail to compile if the sizes don't match up:
struct IVec2(i32, i32);
impl IVec2 {
fn parse(b: [u8; 8]) -> Self {
let (first, second) = b.split_array();
IVec2(i32::from_le_bytes(first),
i32::from_le_bytes(second))
}
}Well, here's the thing. These small pieces of code DO show up in actual, real codebases! I've gotten feedback during code reviews along the lines of, "What if the surrounding context is refactored, this tiny, simple piece code could break" and to be perfectly honest, when I get it, I come down to your desk and we have a discussion about whether that kind of feedback is appropriate, and the purpose of code reviews.
(It also always seems like the issue I'm looking at is "fixed in nightly", but some of those features in nightly take a long time to get accepted, and the ergonomics of split_array() seem a bit dubious to me. Are you going to chain three split_array() for four fields? Obviously, for simple serialization and deserialization there are a ton of different options to automate this code away, but it's nice to be able to write simple code like this when appropriate, and the ergonomics of simple tasks matter.)
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.See: 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.
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.
But it leads to just a TON of features and approaches to learn.
That said, I do think there's a place for "unwrap" in eg. tests.
Past that, we're going to have code that calls unwrap(), unless we want what should be simple to consist mostly of pattern matching boilerplate (and functions returning Result<T,...> when they could just be T).
* - Of course, now you have to deal with a tactic language / dependent types, and those could arguably be called a bear in and of themselves ;)
fn try_from(value: U) -> Result<Self, Infallible>
In which case you could potentially avoid the need for an unwrap. d[0..4].try_into()
The type of the result is something like: Result<[u8; 4], TryFromSliceError>
How do I convert that into Result<[u8; 4], Infallible>
As far as I can tell, Infallible is there because you're implementing a trait which returns an error, but you don't have an error to return at all.