Rust notes

错误处理

shortcuts for panic on error: unwrap and expect

  • unwrap

    • Result<T, E>

      • 如果Ok, 返回值

      • 如果Err, panic!

  • expect

    • 错误时,提供一个消息并panic!

propagating errors

使用?快速的替代多余代码返回错误.

一个示例:

fn read_username_from_file() -> Result<String, io::Error> {
    let username_file_result = File::open("hello.txt");
    let mut username_file = match username_file_result {
        Ok(file) => file,
        Err(e) => return Err(e),
    };
    let mut username = String::new();
    match username_file.read_to_string(&mut username) {
        Ok(_) => Ok(username),
        Err(e) => Err(e),
    }
}

使用?简单替换.

fn read_username_from_file() -> Result<String, io::Error> {
    let mut username_file = File::open("hello.txt")?;
    let mut username = String::new();
    username_file.read_to_string(&mut username)?;
    Ok(username)
}

?可以串联使用, 上面代码简化为:

fn read_username_from_file() -> Result<String, io::Error> {
    let mut username = String::new();
    File::open("hello.txt")?.read_to_string(&mut username)?;
    Ok(username)
}

Trait

traitinterface的区别.

trait bounds

fn some_function<T: Display + Clone, U: Clone + Debug>(t: &T, u: &U) -> i32 {

可以使用where改写成:

fn some_function<T, U>(t: &T, u: &U) -> i32
    where T: Display + Clone,
          U: Clone + Debug
{

Borrow Checker

borrow checker通过对比borrow的作用域(scope)来检查borrow是否有效.

fn main() {
    let r;                // ---------+-- 'a
                          //          |
    {                     //          |
        let x = 5;        // -+-- 'b  |
        r = &x;           //  |       |
    }                     // -+       |
                          //          |
    println!("r: {}", r); //          |
}                         // ---------+

Listing 10-17: Annotations of the lifetimes of r and x, named ‘a and ‘b, respectively