rukยทsi

๐Ÿฆ€ Rust
Result

Updated at 2024-01-04 06:26

Functions that can fail controllably should return a Result. Result signifies a conditional return that might be OK or might have an error. unwrap if you want to crash on failure, match if you want to do error handling and such.

// enum Result<T, E> {
//     Ok(T),
//     Err(E),
// }

fn main() {
    let s = std::str::from_utf8(&[240, 159, 141, 137]);
    println!("{:?}", s);
    // prints: Ok("๐Ÿ‰")

    let s = std::str::from_utf8(&[195, 40]);
    println!("{:?}", s);
    // prints: Err(Utf8Error { valid_up_to: 0, error_len: Some(1) })

    let s = std::str::from_utf8(&[240, 159, 141, 137]).unwrap();
    println!("{:?}", s);
    // prints: "๐Ÿ‰"

    match std::str::from_utf8(&[240, 159, 141, 137]) {
        Ok(s) => println!("{}", s),
        Err(e) => panic!("{}", e),
    }
    // prints: ๐Ÿ‰

    if let Ok(s) = std::str::from_utf8(&[240, 159, 141, 137]) {
        println!("{}", s);
    }
    // prints: ๐Ÿ‰
}

? is the shorthand for error bubbling.

fn main() -> Result<(), std::str::Utf8Error> {
    match std::str::from_utf8(&[240, 159, 141, 137]) {
        Ok(s) => println!("{}", s),
        Err(e) => return Err(e),
    }
    Ok(())

    // or, equally with the shorthand:

    let s = std::str::from_utf8(&[240, 159, 141, 137])?;
    println!("{}", s);
    Ok(())
}

Sources