Option<T>
Option<T> represents a present value, Some(T), or an absent value, None. The prelude does not declare an unwrap method.
Methods and types
These signatures summarize lib/runtime/VexArch/src/prelude/option.vx. Methods with a by-value receiver consume the option according to its payload's ownership rules; isSome, isNone, clone, and asRef borrow it. Option<T> is Copy only when its concrete payload supports Copy.
| Method | Signature and result |
|---|---|
isSome, isNone | (&Option<T>) -> bool |
or | (Option<T>, T) -> T: value or fallback payload |
orElse, rescue | (Option<T>, fn(): T) -> T: value or computed fallback payload |
map | (Option<T>, fn(T): U) -> Option<U> |
flatMap | (Option<T>, fn(T): Option<U>) -> Option<U> |
filter | (Option<T>, fn(T): bool) -> Option<T> |
clone | (&Option<T>) -> Option<T> where T: Clone |
asRef | (&Option<T>) -> Option<&T> |
asMut | (&Option<T>!) -> Option<&T!> |
take | fn !(self: &Option<T>!) take(): Option<T> |
replace | fn !(self: &Option<T>!) replace(value: T): Option<T> |
or does not take another Option<T> as a fallback for an Option<T>; its fallback is the payload T. Likewise, orElse returns T, not another option. Use match when selecting between optional sources. flatMap is the name declared for Option-returning composition; the prelude does not declare an andThen alias. It also does not declare okOr or okOrElse; use an explicit match for conversions instead of assuming those methods exist. take returns the old option and leaves None behind. replace(value) returns the old option and leaves Some(value). They use the mutating fn ! marker. Check their ownership effects before using the old or replacement value; this marker is distinct from an unsafe fn declaration.
Options also support == when T: Eq: two absent options compare equal; two present options compare their payloads; a present and absent option differ.
A runnable example
fn even_half(n: i32): Option<i32> {
if n % 2 == 0 { return Some(n / 2); }
return None;
}
fn main(): i32 {
let value: Option<i32> = Some(10);
let missing: Option<i32> = None;
$println(value.isSome());
$println(missing.isNone());
$println(value.or(99));
$println(missing.orElse(|| 7));
let doubled: Option<i32> = value.map(|n: i32| n * 2);
$println(doubled.or(0));
let half: Option<i32> = value.flatMap(even_half);
$println(half.or(0));
let filtered: Option<i32> = value.filter(|n: i32| n > 20);
$println(filtered.or(-1));
return 0;
}Run vex run option-example.vx. The expected stdout is:
true
true
10
7
20
5
-1The closures use explicit parameter types. Some unannotated closures are inferred successfully, while others are not; annotate a parameter when inference is insufficient. See Closures.
Fallback and propagation
A normal function argument such as option.or(expensive()) is evaluated before calling or, even if the option is Some. The callback passed to orElse is called only for None. For the ?? operator, option ?? expensive() also evaluates the right side only for None; option !> || expensive() is another fallback form. See Operators for ??, !>, and ?.
A match makes the paths explicit and can construct a result:
fn require_value(option: Option<i32>): Result<i32, i32> {
return match option {
Some(value) => Ok(value),
None => Err(1),
};
}A ? applied to None in a function returning an Option propagates None.
Collecting options
The following complete example uses an explicit match and a Vec<i32> to compact present values. It covers mixed, all-present, and all-absent input. The result contains the payloads themselves; retaining Some wrappers would produce a different element type.
fn collect(values: [Option<i32>; 4]): Vec<i32> {
let! output = Vec.new<i32>();
let! i: usize = 0;
while i < 4 {
match values[i] {
Some(value) => { output.push(value); },
None => {},
};
i = i + 1;
}
return output;
}
fn main(): i32 {
let mixed: [Option<i32>; 4] = [Some(1), Some(2), None, Some(4)];
let all: [Option<i32>; 4] = [Some(1), Some(2), Some(3), Some(4)];
let none: [Option<i32>; 4] = [None, None, None, None];
let a = collect(mixed);
let b = collect(all);
let c = collect(none);
if a.len() != 3 || a[0] != 1 || a[1] != 2 || a[2] != 4 { return 1; }
if b.len() != 4 || b[0] != 1 || b[1] != 2 || b[2] != 3 || b[3] != 4 { return 2; }
if c.len() != 0 { return 3; }
$println(a.len()); $println(a[0]); $println(a[1]); $println(a[2]);
$println(b.len()); $println(b[0]); $println(b[1]); $println(b[2]); $println(b[3]);
$println(c.len());
return 0;
}The mixed output has length 3 and values 1, 2, 4; the all-present output has length 4 and values 1, 2, 3, 4; the all-absent output has length 0. The program prints those lengths and values in that order and exits 0; it returns a nonzero code if a check fails.
Replacing each None with 0 instead would preserve positions and produce [1, 2, 0, 4]; that is a different operation.
Transfer an owning payload out of a reusable slot
take is useful for a pending task or cached value that is consumed once. replace installs a new payload and returns the old one, allowing the caller to process or release it explicitly. Neither operation clones the payload.
fn runNext(pending: &Option<string>!): usize {
return match pending.take() {
Some(command) => { $println(command); command.len() },
None => 0,
};
}
fn main(): i32 {
let! pending: Option<string> = Some("deploy".toString());
let previous = pending.replace("backup".toString());
match previous {
Some(command) => { $println(f"replaced: {command}"); },
None => { return 1; },
};
if runNext(&pending!) != 6 || pending.isSome() { return 2; }
if runNext(&pending!) != 0 { return 3; }
let empty = pending.replace("verify".toString());
if empty.isSome() || runNext(&pending!) != 6 { return 4; }
return 0;
}The program prints replaced: deploy, backup, and verify, then exits 0. Here processing a command prints its name. After runNext, the slot contains None, so a second call does no work. Replacing that empty slot installs a new owned string and returns None. Each successful take transfers the string to the match arm; the slot no longer owns that string.