std::optional (v0.2.2)
Optional value container with presence checks and safe access.
Latest
Overview
std::optional provides Optional[T], a container that may or may not hold a value. It represents an optional result without using null pointers.
Use some to wrap a value and none for absence. hasValue, isSome, and isNone report state, while unwrap returns the contained value and unwrapOr or valueOr give fallbacks.
Source: thrustc/std/v0.2.2/optional.thrust
Public Signatures
Exported declarations for this module snapshot.
struct Optional [T] @public {
fn some [T] (item: T) Optional[T] @public;
fn none [T] () Optional[T] @public;
fn hasValue [T] (optional: ptr[Optional[T]]) bool @public;
fn isSome [T] (optional: ptr[Optional[T]]) bool @public;
fn isNone [T] (optional: ptr[Optional[T]]) bool @public;
fn unwrap [T] (optional: ptr[Optional[T]]) T @public;
fn unwrapOr [T] (optional: ptr[Optional[T]], fallback: T) T @public;
fn valueOr [T] (optional: ptr[Optional[T]], fallback: T) T @public;
fn set [T] (optional: ptr[Optional[T]], value: T) void @public;
fn replace [T] (optional: ptr[Optional[T]], value: T) Optional[T] @public;
fn clear [T] (optional: ptr[Optional[T]]) void @public;
fn take [T] (optional: ptr[Optional[T]]) Optional[T] @public;
fn orElse [T] (optional: ptr[Optional[T]], fallback: Optional[T]) Optional[T] @public;
fn fromPtr [T] (value: ptr[T]) Optional[ptr[T]] @public;
fn ptrOrNull [T] (optional: ptr[Optional[ptr[T]]]) ptr[T] @public;
Behavior and Use
Operations that return a new Optional transfer ownership to the caller, so the previous container no longer owns the value.
Examples
import std::optional;
// Wrap a value so callers can tell "present" from "absent" without using null.
fn main() s32 @public {
var theme := optional::some[s32](1);
if optional::hasValue(ref theme) {
return optional::unwrap(ref theme);
}
return 0;
}
import std::optional;
// When a value is missing, fall back to a safe default instead of failing.
fn main() s32 @public {
var setting := optional::none[s32]();
if optional::isNone(ref setting) {
return optional::unwrapOr(ref setting, -1);
}
return optional::unwrap(ref setting);
}
import std::optional;
// Try a primary source and fall back to a secondary one when it is empty.
fn main() s32 @public {
var primary := optional::none[s32]();
var secondary := optional::some[s32](20);
var result := optional::orElse(ref primary, secondary);
return optional::unwrap(ref result);
}
import std::optional;
// Lift a raw pointer into an optional: empty when null, holding it otherwise.
fn main() s32 @public {
var value: s32 = 7;
var wrapped := optional::fromPtr[s32](ref value);
var pointer := optional::ptrOrNull(ref wrapped);
if pointer != nullptr {
return (deref pointer);
}
return 0;
}
Notes
- Use isNone before unwrap when the value can be absent.
- optional::Optional is also used by other containers such as vector::next.