Rust——枚举

当一个变量有几种确定的取值情况下,可以将它定义为枚举类型。如性别选择(男/女)

通过      枚举名::枚举值     来访问获取枚举值

1.无参数枚举类型

  

1
2
3
4
5
6
7
8
9
10
11
12
#[derive(Debug)]
enum Sex{     //无参数枚举类型
    male,
    female,
}
 
fn main(){
    let lilei = Sex::male;
    let lily = Sex::female;
   //结构体/枚举类型输出均{:?}
    println!("lilei is a {:?} and lily is a {:?}",lilei,lily);
}

 输出结果:

 

2.含参数枚举类型

   区别于无参数枚举类型地方是,可以给枚举成员添加  元组属性

  

复制代码
#[derive(Debug)]
enum PayAccount{      ///支付帐号,带参数枚举类型
    AlipayAccount(String),
    WechatAccount(String),
    BankAccount(u64),
}

enum People{      ///带参数枚举类型
    ChinesePeople{nation:String,totalnumber:u128},
    AmericanPeople{totalnumber:u128},
    JapanesePeople{height:f64},
}



fn main(){
    let _alibaba = PayAccount::AlipayAccount(String::from("efun@qq.com"));
    let _wechat = PayAccount::WechatAccount(String::from("onlyefun"));
    let _bank = PayAccount::BankAccount(111122223333444);

    let zhonghuijie = People::ChinesePeople{
        nation:String::from("han"),totalnumber:14_000_000_000_000_000};
    


    match zhonghuijie{
        People::AmericanPeople{totalnumber}=>{
            println!("American number is {}",totalnumber);
        },
        People::ChinesePeople{nation,totalnumber}=>{
            println!("Chinese nation is {},totalnumber is {}",nation,totalnumber);
        },
        People::JapanesePeople{height}=>{
            println!("Japanese height is {}",height);
        }
    }
    println!("alibaba account is {:#?}",_alibaba);
    
    println!("Run End");
}
复制代码

运行结果:

  

 

以上代码在VS Code中运行,结果如下:

 

 中间少了邮箱地址邮件地址显示

 

去掉字符@后,正常显示

 

posted @   echo-efun  阅读(388)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示