Type for operations that can fail.
Result is the type that can be used to express fallible operations in the type system.
Alumina does not have exceptions. Value Result<T, E>
can be either a successfull value of
type T
or an error value E
, usually in some form representing the failure that happened.
enum ExecutableType {
ELF,
PE
}
struct Error {}
fn executable_type(contents: &[u8]) -> Result<ExecutableType, Error> {
use std::string::starts_with;
if contents.starts_with("MZ") {
Result::ok(ExecutableType::PE)
} else if contents.starts_with("\x7FELF") {
Result::ok(ExecutableType::ELF)
} else {
// Invalid executable
Result::err(Error {})
}
}
let result = executable_type("\x7f\x45\x4c\x46\x02\x01\x01\x00...");
if result.is_err() {
eprintln!("Invalid executable");
} else {
// e.g. result.unwrap();
// do something with it
}
Run this example
Result is commonly used with the try operator (?
) so that fallible functions can
be composed easily by bailing early.
Result values can also be transformed without unwrapping them using combinators such as map and and_then, and converted into Option with get/get_err.
Structs
Either a success value or an error value.