result¶
Result is either a success or a failure that carries a reason. It is part of
the prelude, so it needs no import.
The type¶
Result is an ordinary candela enum with a type parameter for each side:
You construct and match the variants directly:
Neither constructor needs a type argument: Ok(v) decides the success type and
Err(e) the error type, so a function that returns both hands back a Result
with each side typed, and the value bound in an arm keeps the type that went in.
struct Config {
port: int,
}
fn load(text: string) -> Result<Config, string> {
if text.parse<int>() is Some(port) {
return Ok(Config { port: port });
}
return Err("not a port: " + text);
}
fn main() {
match load("8080") {
Ok(config) => { print(config.port); }
Err(reason) => { print(reason); }
}
}
A constructor names only its own side, so Ok(2) on its own is a
Result<int, any> and goes wherever a Result<int, E> is expected. See
enums for the enum and match syntax, and
generics for type parameters.
A Result is a value you pass around and inspect. It is separate from the
language's raised errors, which unwind to a try/catch; see
error handling.
x? reads the value out of an Ok and hands an Err back to the caller of the
function it is written in, which has to return a Result with the same error
type:
fn port(text: string) -> Result<int, string> {
if text.parse<int>() is Some(n) {
return Ok(n);
}
return Err("not a port: " + text);
}
fn next_port(text: string) -> Result<int, string> {
let p = port(text)?;
return Ok(p + 1);
}
fn main() {
print(next_port("8080"));
print(next_port("http"));
}
The module is pure candela, so it compiles into a .cdlb artifact and runs under
candela-vm with no dynamic library.
Methods¶
The helpers are methods on the result value, defined in an impl Result<T, E>
block.
is_ok¶
- Returns: a bool, true when the result is
Ok.
is_err¶
- Returns: a bool, true when the result is
Err.
unwrap¶
- Returns: the success value.
- Raises:
called unwrap on an Err resultwhen the result isErr. The message does not include the error payload; read it withunwrap_err.
unwrap_err¶
- Returns: the error value.
- Raises:
called unwrap_err on an Ok resultwhen the result isOk.
unwrap_or¶
default: the value to return when the result isErr. It has the result's own success type.- Returns: the success value, or
default. - Raises: nothing.
map¶
f: takes the success value, returns the mapped value.- Returns:
Ok(f(v))for anOk(v), and theErrunchanged.fis not called on anErr.
map_err¶
f: takes the error value, returns the mapped error.- Returns:
Err(f(e))for anErr(e), and theOkunchanged.fis not called on anOk.
and_then¶
f: takes the success value and returns a result of its own.- Returns:
f(v)for anOk(v), and theErrunchanged.fis not called on anErr. Use it to chain steps that may each fail, wheremapwould give you a result inside a result.
ok¶
- Returns:
Some(v)for anOk(v), andNonefor anErr, which drops the error. See option.