Pregunta

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.

¿Fue útil?

Solución

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.

Otros consejos

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<int> 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<int>; // type
opt = Some(1); // constructor
opt = None; // other constructor
match opt {
  Some(x) => { // pattern
    println!("Got {}", x);
  }
  None => { // other pattern
    println!("Got nothing");
  }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top