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