result¶
Result is either a success or a failure that carries a reason.
The type¶
Result is an ordinary candela enum with a type parameter for each side:
Importing the module brings the variants into scope, so you construct and match them directly:
import "std/result";
fn main() {
let r = Ok(5);
match r {
Ok(v) => { print(v); }
Err(e) => { print(e); }
}
}
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.
import "std/result";
struct Config {
port: int,
}
fn load(text: string) -> Result<Config, string> {
if text.is_int() {
return Ok(Config { port: int(text) });
}
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.
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; importing the module brings them in.
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. The module imports option for this, so a program that importsstd/resulthasSomeandNonein scope as well, and importing both modules is fine.