enum IpAddrKind{
V4,
V6,
}
IpAddrKind
就是一个可以在代码中使用的自定义数据类型#[derive(Debug)]
enum IpAddrKind {
V4,
V6,
}
#[derive(Debug)]
struct IpAddr {
kind: IpAddrKind,
address: String,
}
fn main() {
let local = IpAddr {
kind: IpAddrKind::V4,
address: String::from("127.0.0.1"),
};
let loopback = IpAddr {
kind: IpAddrKind::V6,
address: String::from("::1"),
};
println!("The local address is {}", local.address);
dbg!(&loopback);
}
enum IpAddr{
V4(u8,u8,u8,u8);
V6(String),
}
let local = IpAddr::V4(127.0.0.1);
let loopback = IpAddr::V6(String::from("::1"));
Quit
没有关联任何数据Move
类似结构体包含命名字段Write
包含单独一个String
ChangeColor
包含三个 i32
enum Message{
Quit,
Move { x: i32,y: i32},
Write(String),
ChangeColor(i32,i32,i32),
}
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
// 效果同上
// struct QuitMessage;
// struct MoveMessage {
// x: i32,
// y: i32,
// }
// struct WriteMessage(String);
// struct ChangeColor(i32, i32, i32);
impl Message {
fn call(&self) {}
}
fn main() {
let message = Message::Write(String::from("自强不息"));
message.call();
}
Option
enum Option<T>{
None,
Some<T>,
}
match
是一种极其强大的控制流运算符enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn main() {
let coin = Coin::Penny;
value_in_cents(coin);
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => {
println!("Lucky penny"); // Lucky penny
1
}
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
#[derive(Debug)]
enum usState {
Alabama,
Alaska,
}
enum Coin {
Penny,
Nickel,
Dime,
Quarter(usState),
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => 1,
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter(state) => {
println!("state quarter from: {:#?}!", state);
25
}
}
}
fn main() {
value_in_cents(Coin::Quarter(usState::Alaska));
}
Option
;如果其中含有一个值,将其加1,如果其中没有值,函数应该返回None值fn main() {
let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
}
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}
use rand::Rng;
fn main() {
let num = rand::thread_rng().gen_range(1..=10);
games_rules(num)
}
fn games_rules(num: i32) {
// error,对可能出现的结果没实现全覆盖
match num {
3 => add_fancy_hat(),
// 7 => remove_fancy_hat(),
// _ => move_player(),
}
}
fn add_fancy_hat() {
println!("获得一顶帽子");
}
fn remove_fancy_hat() {
println!("失去一顶帽子")
}
fn move_player() {
println!("移动一步");
}
_
代表其他可能性use rand::Rng;
fn main() {
let num = rand::thread_rng().gen_range(1..=10);
games_rules(num)
}
fn games_rules(num: i32) {
match num {
3 => add_fancy_hat(),
7 => remove_fancy_hat(),
_ => move_player(),
}
}
fn add_fancy_hat() {
println!("获得一顶帽子");
}
fn remove_fancy_hat() {
println!("失去一顶帽子")
}
fn move_player() {
println!("移动一步");
}
let mut count = 0;
match Coin {
Coin::Quarter(state) => println!("State quarter from {:?}!",state),
_ => count += 1,
}
或者可以使用这样的if let 和 else 表达式
let mut count = 0;
if let Coin::Quarter(state) = coin {
println!("State quarter from {:?}!",state);
} else {
count += 1;
}