Are they the same? I can sometimes see the documentation use them as if they were equal.
2 Answers
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");
}
}
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:
-
1Does 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.– JeroenJun 3, 2014 at 19:05
-
5To 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 sincematch
expressions must be exhaustive, you then must handle theNone
branch explicitly.– dwernerJun 3, 2014 at 19:06 -
1@JeroenBollen - It's not wrong to say it returns an
Option
if it always returnsSome
sinceSome
is anOption
.– LeeJun 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 valueSome(blah)
for someblah
, neverNone
. It's like saying "this function always returns 0". 0 is not a type, it's a value, but the statement still makes sense.– user395760Jun 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