text

source of std::option

1// The optional value: a payload (`Some`) or its absence (`None`).2//3// Option is a lang item (LANGUAGE_SPEC.md section 6.1a) at the canonical4// path std::option::Option: the compiler's cursor-protocol `for` lowering5// matches on the Option returned by an iterator's `next`. Nothing here is6// otherwise special; it is an ordinary generic enum. An option of a7// disposable payload is disposable itself (section 5.2).89import std::dispose;10import std::string;11import std::format;1213exp type Option<T> : Disposable if (T: Disposable) + Format if (T: Format) = enum {14    Some: T,15    None,16};1718// Disposes the payload, if any.19exp fn dispose<T: Disposable>(self option: &var Option<T>) {20    if (option is ::Some |&var value|) {21        value.dispose();22    }23}2425// Writes `Some(payload)` or `None` (std::format).26exp fn format<T: Format>(self option: &Option<T>, out: &var String) {27    if (option is ::Some |&value|) {28        out.append(&"Some(");29        value.format(&var out);30        out.push(')');31    } else {32        out.append(&"None");33    }34}3536// True when the option carries a payload.37exp fn is_some<T>(self option: &Option<T>) -> bool => option is ::Some;3839// True when the option is empty.40exp fn is_none<T>(self option: &Option<T>) -> bool => option is ::None;4142// The payload when present, otherwise the given fallback. The payload is43// returned as a copy (deep, when T owns heap); the fallback moves out.44exp fn unwrap_or<T>(self option: &Option<T>, fallback: T) -> T {45    match (option) {46        ::Some |&value| { return copy value; }47        ::None { return move fallback; }48    }49}