31天会用Rust——Day10,枚举

1,简单使用

枚举罗列了所有可能的值。

可以由match表达式进行匹配。

fn main() {
    
    
    let a = Gender::Female;
    
    match a {
    
    
        Gender::Female => println!("F"),
        Gender::Male => println!("M"),
    }
}
enum Gender {
    
    
    Male,
    Female,
}

F

2,附带值

附带元组。

fn main() {
    
    
    let a = Gender::Female(1);
    match a {
    
    
        Gender::Female(v) => println!("F:{}", v),
        Gender::Male(v) => println!("M:{}", v),
    }
}
enum Gender {
    
    
    Male(i32),
    Female(i32),
}

F1

附带类结构体。

fn main() {
    
    
    let a = Gender::Female {
    
     x: 1, y: 2 };
    match a {
    
    
        Gender::Female {
    
     x, y } => println!("F:x{},y{}", x, y),
        Gender::Male {
    
     x, y } => println!("M:x{},y{}", x, y),
    }
}
enum Gender {
    
    
    Male {
    
     x: i32, y: i32 },
    Female {
    
     x: i32, y: i32 },
}

F:x1,y2

3,枚举的方法

枚举也可以有方法。

其中,*self表示解引用。因为match不匹配指针。

fn main() {
    
    
    let a = Gender::Female;
    println!("{}", a.my_string());
}
enum Gender {
    
    
    Male,
    Female,
}
impl Gender {
    
    
    fn my_string(&self) -> String {
    
    
        match *self {
    
    
            Gender::Male => String::from("男"),
            Gender::Female => String::from("女"),
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37284843/article/details/124174010