# Rust notes ## 错误处理 ### shortcuts for panic on error: `unwrap` and `expect` - `unwrap` - 对`Result` - 如果`Ok`, 返回值 - 如果`Err`, `panic!` - `expect` - 错误时,提供一个消息并`panic!` ### propagating errors 使用`?`快速的替代多余代码返回错误. 一个示例: ```rust fn read_username_from_file() -> Result { 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), } } ``` 使用`?`简单替换. ```rust fn read_username_from_file() -> Result { let mut username_file = File::open("hello.txt")?; let mut username = String::new(); username_file.read_to_string(&mut username)?; Ok(username) } ``` `?`可以串联使用, 上面代码简化为: ```rust fn read_username_from_file() -> Result { let mut username = String::new(); File::open("hello.txt")?.read_to_string(&mut username)?; Ok(username) } ``` ## `Trait` `trait`和`interface`的区别. ### trait bounds ```rust fn some_function(t: &T, u: &U) -> i32 { ``` 可以使用`where`改写成: ```rust fn some_function(t: &T, u: &U) -> i32 where T: Display + Clone, U: Clone + Debug { ``` ## Borrow Checker `borrow checker`通过对比`borrow`的作用域(scope)来检查borrow是否有效. ```rust 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