如何在Rust中使用枚举作为值别名?

时间:2018-06-01 02:36:49

标签: rust

在下面的代码中,如何将Interval::Minute用作60

#[derive(Debug)]
enum Interval {
    Minute = 60,
    Hour = 3600,
    Day = 86400,
}


fn main() {
    let interval = 120;
    let minute = Interval::Minute;
    println!("Number of minutes: {:?}", interval/minute);
}

即,如何将其用作基础值的别名?

1 个答案:

答案 0 :(得分:1)

您可以将其强制转换为整数类型:

let minute = Interval::Minute as i32;

另一种选择是在模块中使用const,具体取决于您尝试执行的操作:

mod interval {
    pub const MINUTE: i32 = 60;
}

fn main() {
    let interval = 120;
    let minute = interval::MINUTE;
    println!("Number of minutes: {:?}", interval/minute);
}