Dzwebs.Net

撰写电脑技术杂文十余年

rust之enum通过impl构造函数获取enum中的项的名称及项对应的值

Admin | 2023-2-21 10:54:52 | 被阅次数 | 1183

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

  rust里面的enum枚举,不仅强大,也灵活,同时也相当磨人,下面的例子,给大家介绍一下。

  通过impl构造enum自己的函数,获取枚举对应项的名称及项对应的值。

#[derive(Debug,Copy, Clone)]
enum Week {
  Monday = 1,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday,
}
impl Week{
fn is_weekend(self) ->bool {
if self as u8 > 5 {
return true
}
false
}
fn getWeekname(self) -> Week{
match self{
Week::Monday => self,
Week::Tuesday => self,
Week::Wednesday => self,
Week::Thursday => self,
Week::Friday => self,
Week::Saturday => self,
Week::Sunday => self,


}
}
fn getWeekvalue(self) -> u8{
match self{
Week::Monday => self as u8,
Week::Tuesday => self as u8,
Week::Wednesday => self as u8,
Week::Thursday => self as u8,
Week::Friday => self as u8,
Week::Saturday => self as u8,
Week::Sunday => self as u8,
_ => 0,
}
}
}
fn main(){
let myday = Week::Saturday;
println!("输出是否是周末:{:?}",myday.is_weekend());
println!("输出星期几对应的名称:{:?}",myday.getWeekname());
println!("输出星期几对应的数字:{:?}",myday.getWeekvalue());
}

  运行如上代码,输出的内容是:

  输出是否是周末:true
  输出星期几对应的名称:Saturday
  输出星期几对应的数字:6


该杂文来自: 最新技术

上一篇:rust之json新项添加Vec中的多个struct(即json添加

下一篇:rust泛型T构造函数实现的加减乘除

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计