option
import std::core::option; — in the prelude · source
Types
Option<T>
type enum Option<T> {
Some(T);
None;
}
implement enum Option<T> {
is_some(&this) -> boolean;
is_none(&this) -> boolean;
as_ref(&this) -> Option<T*>;
unwrap_ptr(&this) -> T*;
![sink]
unwrap(&this) -> T;
![sink]
expect(&this, message: string) -> T;
![sink]
unwrap_or(&this, default_value: T) -> T;
![sink]
unwrap_or_else(&this, default_fn: () -> T) -> T;
![sink]
map<U>(&this, f: (T) -> U) -> Option<U>;
![sink]
and_then<U>(&this, f: (T) -> Option<U>) -> Option<U>;
![sink]
or_else(&this, f: () -> Option<T>) -> Option<T>;
take(mut &this) -> Option<T>;
![sink]
ok_or<E>(&this, err: E) -> Result<T, E>;
![sink]
ok_or_else<E>(&this, err_fn: () -> E) -> Result<T, E>;
contains(&this, value: &T) -> boolean
where T: Eq;
}
Option<T> is how Cryo says "there might not be a value here". It replaces the nullable pointer: the compiler will not let you reach the payload without handling the absent case.
match (maybe_port) {
Option::Some(p) => { println(f"port {p}"); }
Option::None => { println("no port configured"); }
}
The ![sink] attribute marks the methods that consume the receiver: after opt.unwrap() the move-checker treats opt as moved, even though the parameter is spelled &this. The unmarked methods leave the receiver live.
Variants
| Variant |
|---|
Some(T) |
None |
Methods
is_some(&this) -> boolean;
is_none(&this) -> boolean;
as_ref(&this) -> Option<T*>;
as_ref(&this) -> Option<T*>;Borrow the contained value in place: Some(v) -> Some(&v), None -> None. The pointer aliases the receiver's payload (no copy is made), so unlike the consuming accessors this is NOT ![sink] - the receiver stays live and keeps ownership of T. The pointer is valid only while the receiver outlives it and is invalidated by anything that moves or overwrites the receiver.
unwrap_ptr(&this) -> T*;
unwrap_ptr(&this) -> T*;Borrow the contained value in place, aborting on None. Like as_ref the pointer aliases the receiver's payload rather than copying it, so the receiver keeps ownership of T and this is NOT ![sink]; the pointer is invalidated by anything that moves or overwrites the receiver.
![sink] unwrap(&this) -> T;
![sink] unwrap(&this) -> T;Return the inner value, aborting on None. Prefer unwrap_or or a match in code that must not panic.
![sink] expect(&this, message: string) -> T;
![sink] expect(&this, message: string) -> T;Like unwrap, but with a caller-supplied message describing the invariant the caller believed held.
![sink] unwrap_or(&this, default_value: T) -> T;
![sink] unwrap_or_else(&this, default_fn: () -> T) -> T;
![sink] unwrap_or_else(&this, default_fn: () -> T) -> T;Use this when the default is expensive and shouldn't be computed in the Some case.
![sink] map<U>(&this, f: (T) -> U) -> Option<U>;
![sink] and_then<U>(&this, f: (T) -> Option<U>) -> Option<U>;
![sink] and_then<U>(&this, f: (T) -> Option<U>) -> Option<U>;Monadic bind: chain operations each of which may be absent.
![sink] or_else(&this, f: () -> Option<T>) -> Option<T>;
take(mut &this) -> Option<T>;
take(mut &this) -> Option<T>;Replace with None and return the previous value.
![sink] ok_or<E>(&this, err: E) -> Result<T, E>;
![sink] ok_or<E>(&this, err: E) -> Result<T, E>;Some(v) -> Ok(v); None -> Err(err).
![sink] ok_or_else<E>(&this, err_fn: () -> E) -> Result<T, E>;
contains(&this, value: &T) -> boolean where T: Eq;
contains(&this, value: &T) -> boolean where T: Eq;True if the option is Some(x) where x.equals(&value).
Querying and unwrapping
unwrap panics on None and expect panics with your message; unwrap_or takes a fallback value and unwrap_or_else computes one only when needed.
Borrowing without consuming
unwrap and friends take the value out. When the payload owns heap storage and you only want to look at it, borrow instead:
as_ref(&this) -> Option<T*>—Some(v)becomesSome(&v),NonestaysNone. The pointer aliases the receiver's payload rather than copying it, so the receiver keeps ownership.unwrap_ptr(&this) -> T*— the same borrow, aborting onNone, and one less layer to unwrap.
Both pointers are invalidated by anything that moves or overwrites the receiver.
Transforming
map, and_then, and or_else chain computations without unwrapping. take() replaces the receiver with None and returns what was there. ok_or and ok_or_else turn the absent case into an Err.
The ?? operator is sugar over the same idea: opt ?? fallback yields the payload or fallback, evaluating the fallback only on None.
Trait implementations
implement<T> trait Clone for enum Option<T> where T: Clone
implement<T> trait Eq for enum Option<T> where T: Eq
implement<T> trait Display for enum Option<T> where T: Display
std::fmt::display
implement<T> trait Debug for enum Option<T> where T: Debug
std::fmt::display
Display and Debug both render Some(...) / None; the difference is which trait the payload goes through.
type struct Name { ... }
type enum Name { ... }
type trait Name { ... }
type union Name { ... }Begins a type declaration; the keyword that follows says which kind. On its own, type Name = Existing; declares an alias.
type enum Name {
Unit,
Payload(T),
Named { x: i32 },
}An algebraic data type. Variants may be bare or carry a tuple or struct payload, and a match on an enum must cover every variant. Name::Variant names a variant; methods are added with implement enum Name { ... }.
type enum Option<T> {
Some(T);
None;
}Option: a value that may be absent.
type parameter TOption::Some(T)type parameter TOption::Noneimplement struct Name { ... }
implement trait Trait for Type { ... }
implement u64 { ... }Adds methods to a type outside its declaration. implement struct T (or enum, or a bare primitive) opens an inherent block; implement trait Tr for T supplies a trait's methods for one type. Resolution is at compile time - no dynamic dispatch.
implement enum Name { ... }Names the enum an inherent block extends - the only way to give an enum methods.
language referenceOption::is_some(&this) -> boolean&this
mut &this
thisThe receiver of a method. Its first parameter declares how the method takes it: &this borrows read-only, mut &this borrows exclusively, and this / mut this move the value in and consume it. In the body, this.field reaches the members.
Option::is_none(&this) -> booleanOption::as_ref(&this) -> Option<T*>Borrow the contained value in place: Some(v) -> Some(&v), None -> None. The pointer aliases the receiver's payload (no copy is made), so unlike the consuming accessors this is NOT ![sink] - the receiver stays live and keeps ownership of T.
type parameter TOption::unwrap_ptr(&this) -> T*Borrow the contained value in place, aborting on None. Like as_ref the pointer aliases the receiver's payload rather than copying it, so the receiver keeps ownership of T and this is NOT ![sink]; the pointer is invalidated by anything that moves or overwrites the receiver.
Option::unwrap(&this) -> TReturn the inner value, aborting on None. Prefer unwrap_or or a match in code that must not panic.
Option::expect(&this, message: string) -> TLike unwrap, but with a caller-supplied message describing the invariant the caller believed held.
(parameter) message: stringprimitive stringNUL-terminated raw string (u8*), matching the C ABI. Length-typed text is Str / String.
Option::unwrap_or(&this, default_value: T) -> T(parameter) default_value: TOption::unwrap_or_else(&this, default_fn: () -> T) -> TUse this when the default is expensive and shouldn't be computed in the Some case.
(parameter) default_fn: () -> TOption::map<U>(&this, f: (T) -> U) -> Option<U>type parameter U(parameter) f: (T) -> Utype parameter UOption::and_then<U>(&this, f: (T) -> Option<U>) -> Option<U>Monadic bind: chain operations each of which may be absent.
(parameter) f: (T) -> Option<U>type parameter UOption::or_else(&this, f: () -> Option<T>) -> Option<T>(parameter) f: () -> Option<T>Option::take(mut &this) -> Option<T>Replace with None and return the previous value.
mut &this
mut &TypeAn exclusive, mutating borrow. As a receiver, mut &this lets the method modify the fields - and callers can see that from the signature alone. As a parameter type, mut &T lets the callee mutate through the reference while the caller keeps ownership.
Option::ok_or<E>(&this, err: E) -> Result<T, E>Some(v) -> Ok(v); None -> Err(err).
type parameter E(parameter) err: Etype parameter EOption::ok_or_else<E>(&this, err_fn: () -> E) -> Result<T, E>(parameter) err_fn: () -> Etype parameter EOption::contains(&this, value: &T) -> boolean
where T: EqTrue if the option is Some(x) where x.equals(&value).
(parameter) value: &Twhere T: Ord + Clone, U: HashConstrains generic parameters to types that implement the listed traits, which is what makes those traits' methods callable on T. Bounds on one parameter join with +; parameters separate with ,. A where on a single method narrows the type's parameter for that method only.
type trait Eq {
equals(&this, other: &This) -> boolean;
}Types that support value equality. equals(a, b) must be reflexive, symmetric, and transitive.
match (subject) {
Pattern(x) => { ... }
_ => { ... }
}The primary discriminator: branches on enum variants, integers, ranges, and destructuring patterns, and the compiler rejects a match that misses a case. There is no fallthrough. As an expression it evaluates to the chosen arm's value, so every arm must produce the same type.
Option::Some(T)ppattern => { body }Separates a match arm's pattern from its body. Arms do not fall through.
Option::Noneimport a::b;
import a::b::{ X, Y };
import a::b as c;
import a::b::*;Brings a module, or selected items from it, into scope. One path per declaration: use the brace form for several items, as to alias, and * for everything public (prefer the brace form; wildcards invite name collisions).
Option::is_some(&this) -> booleanOption::is_none(&this) -> booleanOption::as_ref(&this) -> Option<T*>Borrow the contained value in place: Some(v) -> Some(&v), None -> None. The pointer aliases the receiver's payload (no copy is made), so unlike the consuming accessors this is NOT ![sink] - the receiver stays live and keeps ownership of T.
Option::unwrap_ptr(&this) -> T*Borrow the contained value in place, aborting on None. Like as_ref the pointer aliases the receiver's payload rather than copying it, so the receiver keeps ownership of T and this is NOT ![sink]; the pointer is invalidated by anything that moves or overwrites the receiver.
Option::unwrap(&this) -> TReturn the inner value, aborting on None. Prefer unwrap_or or a match in code that must not panic.
Option::unwrap_or(&this, default_value: T) -> TOption::expect(&this, message: string) -> TLike unwrap, but with a caller-supplied message describing the invariant the caller believed held.
Option::unwrap_or_else(&this, default_fn: () -> T) -> TUse this when the default is expensive and shouldn't be computed in the Some case.
Option::map<U>(&this, f: (T) -> U) -> Option<U>Option::and_then<U>(&this, f: (T) -> Option<U>) -> Option<U>Monadic bind: chain operations each of which may be absent.
std::core::optionOption::or_else(&this, f: () -> Option<T>) -> Option<T>Option::take(mut &this) -> Option<T>Replace with None and return the previous value.
const E: f64 = 2.718281828459045;Result::Ok(T)Result::Err(E)Option::ok_or_else<E>(&this, err_fn: () -> E) -> Result<T, E>Option::contains(&this, value: &T) -> boolean
where T: EqTrue if the option is Some(x) where x.equals(&value).
option ?? fallbackNull-coalescing: unwraps an Option<T> to its T, evaluating fallback only when it is None. Right-associative, so a ?? b ?? c reads a ?? (b ?? c) - every operand but the last is an Option.
type parameter Twhere T: Clone
type trait Name : Base {
method(&this, other: &This) -> Ret;
}Names a set of methods a type may implement. Inside the body This is the implementing type; methods may carry default bodies, and a trait may require a base trait (type trait Ord : Eq). Generic code asks for a trait with where T: Name.
implement trait Trait for Type { ... }Names the type a trait implementation is for. The block that follows supplies the bodies the trait requires.
language referencetype parameter Twhere T: Eq
type parameter Twhere T: Display
type trait Display {
fmt<W>(&this, f: mut &Formatter<W>) -> Result<(), FmtError>
where W: FmtWrite;
}Display / Debug / Formatter.
std::fmt::displaytype parameter Twhere T: Debug
type trait Debug {
fmt<W>(&this, f: mut &Formatter<W>) -> Result<(), FmtError>
where W: FmtWrite;
}function name(count: i32, args...)A variadic parameter: the trailing bucket receives any number of further arguments with C's calling convention, so the function stays ABI-compatible with the printf family. Wrap the bucket in VaArgs to read typed values from it.