9

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

2 Answers 2

10

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");
    }
}
7

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:

5
  • 1
    Does this mean some documentation of Rust is plain wrong? Example: static.rust-lang.org/doc/0.10/std/io/… - That one says the next method always returns Some, while really it returns an Option.
    – Jeroen
    Jun 3, 2014 at 19:05
  • 5
    To add to this; the point of Option types are to represent nullable (None) values without including the notion of the null pointer in the language. Using an enum means you MUST match {} it and since match expressions must be exhaustive, you then must handle the None branch explicitly.
    – dwerner
    Jun 3, 2014 at 19:06
  • 1
    @JeroenBollen - It's not wrong to say it returns an Option if it always returns Some since Some is an Option.
    – Lee
    Jun 3, 2014 at 19:08
  • 2
    @JeroenBollen Its return value is always a value of type Option<...>. But this type overly broad (it's mandated by the iterator trait), and hence the part you refer to informs the reader: The return value is always a value Some(blah) for some blah, never None. It's like saying "this function always returns 0". 0 is not a type, it's a value, but the statement still makes sense.
    – user395760
    Jun 3, 2014 at 19:08
  • 2
    @Jeroen Bollen: it's not incorrect to say that a method always returns a certain value.
    – A.B.
    Jun 3, 2014 at 19:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.