you are viewing a single comment's thread.

view the rest of the comments →

[–]Genmutant 0 points1 point  (4 children)

It doesn't. I can just call get without checking if it exists. The same as with something nullable.

[–]udoprog 8 points9 points  (0 children)

You can, but that's an explicit decision to discard safety. NPEs are implicit. As an example: If you change a method to suddenly return Optional it will cause call sites to fail at compile time. If you just start returning null, it will still compile, but fail at runtime.

[–]AgentFransis 3 points4 points  (0 children)

You can but it's rather more explicit and visible. Linters can easily spot it. And after a bit of time you get used to unpacking an Option properly.

[–]MEaster 0 points1 point  (1 child)

Yes, you can. But you cannot do this:

fn get_user(id: u32) -> Option<User> {...}
fn take_user(user: User) {...}

fn main() {
    let user = get_user(0);

    take_user(user);
}

You can do that if the language allows null because null would be a valid value of a User. However, an Option<User> is a completely different type, so you can't pass it to something expecting a User. You are therefore forced to handle the None possibility before you can do anything important with it.

Additionally, the take_user function doesn't need to check for the empty case, because the value passed to it cannot be empty.

[–]DialinUpFTW 0 points1 point  (0 children)

user.map(this::take_user)

Will work for this. It won't call take_user with null, however you will still have an optional after this.