Result
Result is a richer version of the Option type that
describes possible error instead of possible absence.
That is, Result<T, E> could have one of two outcomes:
Ok(T): An elementTwas foundErr(E): An error was found with elementE
By convention, the expected outcome is Ok while the unexpected outcome is Err.
Like Option, Result has many methods associated with it. unwrap(), for
example, either yields the element T or panics. For case handling,
there are many combinators between Result and Option that overlap.
In working with Cairo, you will likely encounter methods that return the Result type.
Let's see what happens when we successfully and unsuccessfully try to convert a character in a ByteArray to a number:
#[derive(Drop)]
struct ParseIntError {
message: ByteArray,
}
fn char_to_number(c: ByteArray) -> Result<u8, ParseIntError> {
if c.len() != 1 {
return Err(ParseIntError { message: "Expected a single character" });
}
let byte = c[0];
Ok(byte)
}
fn main() {
let result = char_to_number("a");
match result {
Ok(number) => println!("Number: 0x{:x}", number),
Err(error) => println!("Error: {}", error.message),
}
let result = char_to_number("ab");
match result {
Ok(number) => println!("Number: 0x{:x}", number),
Err(error) => println!("Error: {}", error.message),
}
}
In the unsuccessful case, char_to_number() returns an error for us to handle.
We can improve the quality of our error message by being more specific
about the return type and considering explicitly handling the error.