Jeroen
Jeroen

Reputation: 16865

What is the difference between Some and Option in Rust?

Are they the same? I can sometimes see the documentation use them as if they were equal.

Upvotes: 10

Views: 5244

Answers (2)

user395760
user395760

Reputation:

No, they are not the same, and documentation treating them as if they were the same is either wrong, or a misunderstanding on your side. Option is a type (more accurately, a generic type constructor; Option<i32> is a type, and so is Option<String>). Some is a constructor. Aside from acting as a function fn Some<T>(T x) -> Option<T>, it's also used in pattern matching:

let mut opt: Option<i32>; // type
opt = Some(1); // constructor
opt = None; // other constructor
match opt {
    Some(x) => {
        // pattern
        println!("Got {}", x);
    }
    None => {
        // other pattern
        println!("Got nothing");
    }
}

Upvotes: 11

A.B.
A.B.

Reputation: 16660

The Option type is defined as:

enum Option<T> {
    None,
    Some(T),
}

Which means that the Option type can have either a None or a Some value.

See also:

Upvotes: 10

Related Questions