Hacker News new | ask | show | jobs
by woah 2015 days ago
It is the most readable to you because you are used to null. If you're reading Rust, then it's a pretty good assumption that you'll be used to Option<x>.

Null is sloppy because it is the only way in many languages to express something like a union type (in Rust terms, an "enum"). So it gets overloaded to convey information that would be more accurately conveyed by a union type.

The Rust equivalent of null, Option, is just another enum and you can handle it with the standard enum tooling the language gives you such as pattern matching. It also makes you stop and think about what you are doing if you're returning it. In most cases, your intent can be more clearly expressed with an enum other than Option.

This contrived example would be less likely to appear in Rust. Why is there a function called parseFile taking something that might not even be a file?

As an aside, the Rust code could also be written like this:

        fn parse_file(file: Option<File>) -> Result<(), String> {
            if let None = file {
                return Err("File must exist".into());
            }
            // ...
        }
2 comments

> As an aside, the Rust code could also be written like this

Sadly it can't really, because Rust doesn't have control-flow based type refinement like TypeScript.. In TS the type of `file` after the throw is File. In Rust it stays `Option<file>` so you would have to unsafely unwrap it below the if block.

(Unwrap is not unsafe, and in fact, in this code, you would even know that it can never panic. That being said, you're not wrong that this is nicer in TS. You could invert the condition and add an else and it would be not too terrible. I'd still probably go for a ? style.)
Rust’s if-let construct handles that in a nice, explicit, and compact way.
Why use `if let None = file` instead of `if file.is_none()`?