2

In the below code, how to use Interval::Minute as 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);
}

That is, how to use it as an alias for the underlying value?

Greg
  • 8,175
  • 16
  • 72
  • 125
  • @Shepmaster This question is different as the desired solution was to use `interval::MINUTE` vs `Interval::Minute as i32` – Greg Jun 01 '18 at 03:29
  • 2
    Your literal question is "how to use an enum as a value". That's what the duplicate is. You happened to learn about an alternate solution you like and that's great, but that solution has *nothing to do with enums*. – Shepmaster Jun 01 '18 at 03:34

1 Answers1

1

You can cast it to an integer type:

let minute = Interval::Minute as i32;

Another option is to use consts within a module, depending on what you're trying to do:

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

fn main() {
    let interval = 120;
    let minute = interval::MINUTE;
    println!("Number of minutes: {:?}", interval/minute);
}
Jorge Israel Peña
  • 36,800
  • 16
  • 93
  • 123
  • Thank you! Is it also true that `interval::MINUTE` adds no overhead (zero cost abstraction) compared to using an int value of `60`? – Greg Jun 01 '18 at 03:23
  • @Greg what abstraction? `interval::MINUTE` **is an integer**. – Shepmaster Jun 01 '18 at 03:36
  • 1
    @Greg Constants (`const`) are inlined in-place by the compiler wherever they're used, at compile time, so they have no fixed address in memory like a local variable would. I don't know if that's what you're asking. – Jorge Israel Peña Jun 01 '18 at 03:38
  • That clears things up, thank you – Greg Jun 01 '18 at 03:38