Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Rust uses the `Option` type for that (name taken from Scala and ML, it's called `Maybe` in Haskell).

http://static.rust-lang.org/doc/master/std/option/index.html

What's neat is that if you stuff a pointer inside an `Option`, then not only is it guaranteed to be memory-safe but it also compiles down to a plain old nullable pointer at runtime, so there's no extra overhead while still retaining safety.



So it doesn't have "null" but it has "None." On the linked page:

     // Remove the contained string, destroying the Option
     let unwrapped_msg = match msg {
         Some(m) => m,
         None => ~"default message"
     };
Now why is there that ";" at the end? Before that there is a construct without it:

    // Take a reference to the contained string
    match msg {
        Some(ref m) => println!("{}", *m),
        None => ()
    }
And did we have take the "reference" to print the value of m?

And one note more: the linked page doesn't explain that the Some actually introduces "Option" type. It writes about the Option but the code uses just "Some."

     let msg = Some(~"howdy");
Some as a "keyword" seems to have two different semantical purposes, depending if it's in the "match" or not. I don't see that explained too.


Most of this is out of the scope of this tutorial, but is in the comprehensive one.

match is an expression, but let is a statement. In the first example, the match expression is used inside of the let statement, in order to produce what is assigned.

I'm not 100% sure if you _must_ take that reference, but given that it's a pointer, that makes sense. In the previous version, it's simply returning a value, but println! needs the contents, not the pointer itself.

Inside the linked Option enum, it shows both: http://static.rust-lang.org/doc/master/std/option/enum.Optio...

It's an enum like any other.

That said, these are all good points, and this documentation should be improved. Thanks, I'll add this to my list.


The first example is an expression. The result of `match` will be assigned to `unwrapped_msg`.

The second example is a statement. Thus, we're not using the result of the `match` statement.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: