#[derive(Debug)] // so we can inspect the state in a minute
enum UsState {
Alabama,
Alaska,
// --snip--
}
enum Coin {
Penny,
Quarter(UsState),
}
match coin {
Coin::Penny => 1,
Coin::Quarter(state) => {
println!("State quarter from {:?}!", state);
25
}
}
利用match和pattern可以完成对Option的处理:
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
match语句中可以使用_作为一个default分支:
let some_u8_value = Some(0u8);
match some_u8_value {
Some(3) => println!("three"),
_ => (), // ()表示什么都不做
}
上面的语句也可以用如下的if let代替:
if let Some(3) = some_u8_value {
println!("three");
}
if let有一个备选的else分支:
let mut count = 0;
if let Coin::Quarter(state) = coin {
println!("State quarter from {:?}!", state);
} else {
count += 1;
}
modules封装
Packages: A Cargo feature that lets you build, test, and share crates
Crates: A tree of modules that produces a library or executable
Modules and use: Let you control the organization, scope, and privacy of paths
Paths: A way of naming an item, such as a struct, function, or module
容器
Vector
let data =Vec::new();
let data:Vec<i32> =Vec::new();
let vec = vec![1,2,3];
let vec:Vec<i32> =vec![1,2,3];
let v = vec![0; 10]; // 10个0
v.push(3);
let val = v.pop();
let num = v[2]; // Supported by implementing Index & IndexMut traits
异常处理
expect
result.expect("error info");
match result {
Ok(num) => num,
Err(_) => continue, // _算是一个哑变量,可以捕捉任何值
}