2

Let's say I have an enum with two variants including discriminant values:

enum E {
    A = 1,
    B = 2,
}

I can easily convert E into, say, an i32 by doing:

fn f() {
    let e = E::A;
    let i = e as i32;
}

When trying the reverse I would expect the following to work:

fn g(i: i32) {
    let e: E = i.try_into().unwrap(); // E0277: the trait bound `E: std::convert::From<i32>` is not satisfied
}

What is the shortest / most idiomatic way to do this without writing a separate match implementation myself?

left4bread
  • 1,514
  • 2
  • 15
  • 25
  • 2
    The language is missing this IMHO. You should write an issue. – Boiethios Jan 10 '20 at 13:44
  • The answer to the linked question suggest using the `num_derive` crate that includes this functionality. – justinas Jan 10 '20 at 13:47
  • 1
    Technicaly yes, but practically no. It's nice to know a 3rd party crate is available, but I'd like to do this without adding extra dependencies. – left4bread Jan 10 '20 at 13:50
  • Then copy and paste the source code of the dependency into your project. Now you don't have to worry about any pesky dependencies. – Shepmaster Jan 10 '20 at 15:10
  • 1
    @Shepmaster I don't think there is need to be sarcastic. My question was about the shortest way how I can implement this, adding the source of whole dependency surely won't help. – left4bread Jan 10 '20 at 16:49
  • No sarcasm; if a dependency does what you want but you don’t want a dependency, you copy it and delete what isn’t used. There are other linked answers that you would likewise copy and paste and modify, there’s no difference. – Shepmaster Jan 10 '20 at 16:56

0 Answers0