match if
1 #![allow(unused)] 2 fn write_bar(size: u64){ 3 match size{ 4 o if o < 100 => println!("{:?} less than 100", o), 5 o if o < 200 && o > 100 => println!("{:?} between 100-200", o), 6 _ => println!("{:?} bigger than 200", size), 7 } 8 } 9 fn main() { 10 write_bar(10); 11 write_bar(150); 12 write_bar(250); 13 }
println!("{:#?}", 1)
1 #[derive(Debug)] 2 struct Teacher<'a> { 3 name: &'a str, 4 age1: u8 5 } 6 7 #[derive(Debug)] 8 struct Person<'a> { 9 name: &'a str, 10 age: u8 11 } 12 13 fn main() { 14 let name = "Peter"; 15 let mut age = 27; 16 let peter = Person { name, age }; 17 18 age = 22; 19 let lilei = Teacher{ name:"Lilei", age1:age}; 20 // 美化打印 21 println!("{:#?}", lilei); 22 println!("{:#?}", peter); 23 }
println! with param
1 #[derive(Debug)] 2 struct Complex { real: f32, imag: f32 } 3 4 fn main() { 5 println!("The big range is {big:#?} and the small is {small}", 6 small = 0, 7 big = &[1, 2]); 8 println!("Debug: {:#?}", Complex{real: 2.2, imag: 7.2}); 9 }
try!
宏和 ?
一样
write!(f, "{}", value)?; try!(write!(f, "{}", value));
闭包
|val| val + x, 输入和返回类型两者都可以自动推导,而输入变量 名必须指明。
- 声明时使用
||
替代()
将输入参数括起来。 - 函数体定界符(
{}
)对于单个表达式是可选的,其他情况必须加上。 - 有能力捕获外部环境的变量。
fn function (i: i32) -> i32 { i + 1 } let closure_annotated = |i: i32| -> i32 { i + 1 };
valgrind 也可以检查rust的内存泄露
Drop
trait 包含在 prelude 中,所以无需导入它。