Option
Option[Char]
is an enum that represents a Char
value that may or may not be present. It is a common way to handle exceptional cases.
None
means the value is missing.Some(e)
is a wrapper that contains the valuee
.
The [Char]
part in the type is a type parameter, which means the value type in Option
is Char
. We can use Option[String]
, Option[Double]
, etc. We will cover generics later.
The type annotation Option[A]
can be shortened to A?
.
You can use c1.is_empty()
to check if the value is missing and c1.unwrap()
to get the value.
fn first_char(s : String) -> Option[Char] {
if s.length() == 0 {
None
} else {
Some(s[0])
}
}
fn main {
let c1 : Char? = first_char("hello")
let c2 : Option[Char] = first_char("")
println("\{c1.is_empty()}, \{c1.unwrap()}")
println("\{c2.is_empty()}, \{c2}")
}