也有英文版文章
Also this tutorial has been written in English
Check out my Medium
基礎
enum Movement {
Up,
Down,
Left,
Right,
}
fn main() {
let turn_right: Movement = Movement::Right;
}
enum Movement {
Up,
Down,
Left,
Right,
}
fn main() {
let turning_direction: Vec<Movement> = vec![
Movement::Up,
Movement::Down,
Movement::Left,
Movement::Right,
];
}
使用struct進行match分類。
struct movie_ticket {
name: String,
price: i32,
}
fn main() {
let a = movie_ticket {
name: "Spiderverse".to_owned(),
price: 25,
};
match a {
movie_ticket { price: 50, name } => println!("Movie {:?}", name),
movie_ticket { price, .. } => println!("Price = {:?}", price),
}
}
/*
Price = 25
*/
使用enum進行match分類。
enum Ticket {
Backstage(f64, String),
Standard(f64),
Vip(f64, String),
}
fn main() {
let tickets: Vec<Ticket> = vec![
Ticket::Backstage(50.0, "Alice".to_owned()),
Ticket::Standard(15.0),
Ticket::Vip(30.0, "Lauren".to_owned()),
];
for ticket in tickets {
match ticket {
Ticket::Backstage(price, holder) => {
println!("Backstage ticket holder: {:?}, price: {:?}", holder, price);
}
Ticket::Standard(price) => println!("Standard ticket price: {:?}", price),
Ticket::Vip(price, holder) => {
println!("VIP ticket holder: {:?}, price: {:?}", holder, price);
}
}
}
}