option¶
Option is a value that is either present or absent.
The type¶
Option is an ordinary candela enum with a type parameter for what it holds:
Importing the module brings the variants into scope, so you construct and match them directly:
import "std/option";
fn main() {
let o = Some(5);
match o {
Some(v) => { print(v); }
None => { print("nothing"); }
}
}
Some(x) needs no type argument: the value it is given decides the option's
type, so Some(5) is an Option<int> and the value bound in a Some arm comes
back with the type that went in.
import "std/option";
struct Point {
x: int,
y: int,
}
fn nearest(points: Point[]) -> Option<Point> {
if points.len() == 0 {
return None;
}
return Some(points[0]);
}
fn main() {
match nearest([Point { x: 1, y: 2 }]) {
Some(p) => { print(p.x, p.y); }
None => { print("no points"); }
}
}
None names no payload, so on its own it is an Option<any>, which goes
wherever an Option<T> is expected. Name the argument (Option<Point>) where
you want the check. See enums for the enum and match
syntax, and generics for type parameters.
The module is pure candela, so it compiles into a .cdlb artifact and runs under
candela-vm with no dynamic library.
Methods¶
The helpers are methods on the option value, defined in an impl Option<T>
block; importing the module brings them in.
is_some¶
- Returns: a bool, true when the option holds a value.
is_none¶
- Returns: a bool, true when the option is empty.
unwrap¶
- Returns: the contained value.
- Raises:
called unwrap on a None optionwhen the option isNone.
unwrap_or¶
default: the value to return when the option isNone. It has the option's own payload type.- Returns: the contained value, or
default. - Raises: nothing.
map¶
f: takes the contained value, returns the mapped value.- Returns:
Some(f(v))when the option holdsv, andNonewhen it is empty.fis not called on aNone.
and_then¶
f: takes the contained value and returns an option of its own.- Returns:
f(v)when the option holdsv, andNonewhen it is empty.fis not called on aNone. Use it to chain steps that may each come back empty, wheremapwould give you an option inside an option.
or¶
other: the option to fall back on. It has the same payload type.- Returns: this option when it holds a value, and
otherwhen it is empty.
filter¶
pred: takes the contained value and returns a bool.- Returns: this option when it holds a value
predanswers true for, andNoneotherwise.predis not called on aNone.
import "std/option";
fn describe(x) { return "value " + str(x); }
fn main() {
let s = Some(5);
let n = None;
print(s.map(describe).unwrap());
print(n.unwrap_or(0));
}
For a value that carries a reason for being absent, use result instead.