module std::resultsource
The outcome of something that may fail: a value (Ok) or the error
that took its place (Err).
A function that can fail returns a Result and its caller matches on it;
there is no operator propagating an error, so a caller passing one on
writes the match. Like Option, it is an ordinary generic enum, and
== compares two results by their variant and payload. It is written
out (std::format) when both its payloads are, and disposable (section
5.2) when either is.
import std::text;
import std::string;
const port = (text: &[u8]) -> Result<u16, String> {
if (text.parse_integer() is ::Some |n|) {
if (n >= 0 && n < 65536) {
return ::Ok(n to u16);
}
}
return ::Err(String::from(&"not a port"));
};
match (port(&"8080")) {
::Ok |number| { expect_equal(&number, &8080); }
::Err { expect(false); }
}
expect(port(&"http").is_err());
type Resultsource
exp type Result<T, E> : Format if (
T: Format
&& E: Format
) + Disposable if (T: Disposable || E: Disposable) = enum
Variants
Ok: TErr: E
Functions
exp fn dispose<T, E>(self result: &var Result<T, E>)exp fn format<T: Format, E: Format>(self result: &Result<T, E>, out: &var String)exp fn is_ok<T, E>(self result: &Result<T, E>) -> boolexp fn is_err<T, E>(self result: &Result<T, E>) -> boolexp fn ok<T, E>(self result: &Result<T, E>) -> Option<T>exp fn err<T, E>(self result: &Result<T, E>) -> Option<E>
fn disposesource
exp fn dispose<T, E>(self result: &var Result<T, E>)
Disposes the value or the error it holds, when that one is disposable.
fn formatsource
exp fn format<T: Format, E: Format>(self result: &Result<T, E>, out: &var String)
Writes Ok(value) or Err(error) (std::format).
const done: Result<u32, bool> = ::Ok(3);
const failed: Result<u32, bool> = ::Err(true);
expect_equal(&f"{done} {failed}".view(), &"Ok(3) Err(true)");
fn is_oksource
exp fn is_ok<T, E>(self result: &Result<T, E>) -> bool
True when the result holds a value.
const done: Result<u32, u8> = ::Ok(3);
expect(done.is_ok());
fn is_errsource
exp fn is_err<T, E>(self result: &Result<T, E>) -> bool
True when the result holds an error.
fn oksource
exp fn ok<T, E>(self result: &Result<T, E>) -> Option<T>
The value, or None for an error. The value is returned as a copy
(deep, when T owns heap), as Option::unwrap_or returns its payload.
const done: Result<u32, u8> = ::Ok(3);
const failed: Result<u32, u8> = ::Err(1);
expect_equal(&done.ok().unwrap_or(0), &3);
expect(failed.ok().is_none());
fn errsource
exp fn err<T, E>(self result: &Result<T, E>) -> Option<E>
The error, or None for a value, as a copy like ok's.