Reputation: 10520
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
Reputation: 430851
No, there is not.
There are tricks to reduce the amount of code:
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