Comment by pheggs

2 days ago

I don't think it's that people forget it while writing the code, it's that people want their program to work with as little effort as possible and decide to ignore it "for now". And that definitely can happen with Option and Result as well. There's no protection for not checking return values, and it's probably not even possible to protect against (in entirety)

Well they would use `unwrap` if they were lazy, but at least that would be quite visible in the code and would not result in undefined behavior due to operating on a null value. And there might be a group of developers who first choose to use .unwrap. I hope it is the minority.

Given how easy it is to just forward that error to the caller, I think most Rust developers would just choose to do that.

  • While dereferencing a null pointer is technically UB, it practice it leads to a safe trap. So .unwrap is the right comparison. If you always forward the error to the caller, it will also just lead to some random error message at some point, not really different to a crash.

> There's no protection for not checking return values, and it's probably not even possible to protect against (in entirety)

That's exactly what you get with Result and Option, it's impossible to forget.

Compare:

    char* hash = crypt(key, salt);

    // We crash here on the hash derefence, it's no clear from the code
    // that we were supposed to check for NULL or that we forgot. 
    if (!strcmp(hash, expected)) {
    }

To:

    let result: Result<Vec<u8>, Error> = crypt(key, salt);
    // We MUST write this line, which is a very clear signal
    // that we can panic here.
    // This can be grepped for or forbidden.
    let hash: String = result.unwrap();

    // if result == expected { would type error
    if hash == expected {
    }

  • That's exactly what I mean. And I have seen a huge amount of unchecked unwraps in production code in the past years

    • Sure, but it's far better than the C code and I don't think in Rust a library would start returning `Ok` with sentinel values to "fix" shit calling code. Maintainers would, rightfully, tell people to fix their code.

      10 replies →