«

Rust - 枚举

ljierui 发布于 阅读:111 技术杂谈


1、枚举

1.1、定义枚举

// 定义枚举类型
enum IpAddrKind {
    v4,
    v6
}
fn main() {
    // 定义枚举的值
    let fout = IpAddrKind::v4;
    let six = IpAddrKind::v6;

    route(fout);
    route(six);
    route(IpAddrKind::v4)
}

fn route(ip_kind:IpAddrKind){}

1.2、把数据附加到枚举类型中

// 定义枚举类型
enum IpAddrKind {
    v4,
    v6
}

struct IpAddr{
    Kind :IpAddrKind,
    address : String,
}
fn main() {
    let home = IpAddr{
        Kind : IpAddrKind::v4,
        address : String::from("127.0.0.1"),
    };

    let loopback = IpAddr{
        Kind : IpAddrKind::v6,
        address : String::from("::1"),
    };
}

1.3、把数据附加到枚举变体中

// 定义枚举类型
enum IpAddrKind {
    v4(u8,u8,u8,u8),
    v6(String),
}

fn main() {
    let home = IpAddrKind::v4(127, 0, 0, 1);
    let loopback = IpAddrKind::v6(String::from("::1"));
}

1.4、为枚举定义方法

// 定义枚举类型
enum IpAddrKind {
    v4(u8,u8,u8,u8),
    v6(String),
}

impl IpAddrKind {
    fn call(&self){}
}

fn main() {
    let home = IpAddrKind::v4(127, 0, 0, 1);
    let loopback = IpAddrKind::v6(String::from("::1"));

    home.call();
    loopback.call();
}

1.5、Option枚举

fn main() {
   let some_number = Some(5);
   let some_String = Some("A String");

   let absent_number : Option<i32> = None;
}

1.6、match控制流运算符

enum Coin {
    Penny,
    Nickkel,
    Dime,
    Quarter,
}

fn value_in_cents(coin:Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Dime => 5,
        Coin::Nickkel => 10,
        Coin::Quarter => 20,
    }
}

rust语言学习

推荐阅读: