anderspitman
anderspitman

Reputation: 10520

Is there a more succinct way to use an enum especially when it only has primitive types?

I'm using an enum for polymorphism in Rust. I need to have a vector that can have integers or floating point values in it:

enum Value {
    Float(f32),
    Int(i32),
}

let vec = Vec::<Value>::new();
vec.push(Value::Int(0));
vec.push(Value::Float(1.0));

Is there a more succinct way to do this, particularly when you're only using primitive types?

Upvotes: 0

Views: 392

Answers (1)

Shepmaster
Shepmaster

Reputation: 430851

No, there is not.

There are tricks to reduce the amount of code:

  1. There's no need to specify the type of the vector.
  2. You could construct the vector all at once.
  3. You could import the enum variants.
fn main() {
    use Value::*;
    let vec = vec![Int(0), Float(1.0)];
}

it mostly feels strange that I'm effectively just renaming the primitive types

That's just an artifact of your program. For example, there's no real difference to the computer between your enum and this one:

enum MagicSpell {
    Multiplier(f32),
    NumberOfStomachs(i32),
}

However, the semantics (a.k.a. the names) are highly different.

Upvotes: 1

Related Questions