← Back to context

Comment by K0nserv

2 days ago

`Option<String>` or `Result<String>` forces the check at the callsite. Unlike C, you cannot forget that the function can error. This absolutely helps prevent issues like this.

Now, the decision to return `"*"` instead of letting poorly written code crash on `NULL` is not good either.

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 {
        }