You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Rust中使用含原始类型的枚举实现多态,是否有更简洁写法?

Using Raw Types for a Mixed Int/Float Vector in Rust

Great question! Let's start by noting that your enum approach is actually the idiomatic Rust way to handle a collection of values that can be either integers or floats—it's type-safe, compile-time checked, and has minimal runtime overhead.

But to answer your question about using raw types: there's no single built-in raw type that can natively represent both i32 and f32 while preserving all their properties. However, there are a couple of tradeoff-based shortcuts if you're willing to relax some requirements:

Option 1: Use Vec<f32> (if precision and type distinction aren't critical)

If all your integers fit within the exact integer range of f32 (which is up to 2^24—about 16 million), you can store everything as a float. This is super concise:

let mut vec = Vec::new();
vec.push(0.0); // Store integer as float
vec.push(1.0);

Caveats:

  • You lose the ability to distinguish whether a value was originally an integer or float (if that matters for your use case).
  • Integers larger than 2^24 will lose precision when converted to f32, since floats can't represent all large integers exactly.

Option 2: Is there a "better" raw type alternative?

No—Rust's static type system enforces that all elements in a Vec are the same type. Raw types like i32, f32, i64, etc., are all single-purpose, so none can natively handle mixed integer/float values without compromises.

Why your enum approach is still the best choice for most cases

Your original code is already pretty concise, and it solves the problem without tradeoffs:

#[derive(Debug)] // Add this to make debugging easier
enum Value { Float(f32), Int(i32) }

let mut vec = Vec::new();
vec.push(Value::Int(0));
vec.push(Value::Float(1.0));
  • It preserves type information (you can pattern-match to tell integers apart from floats).
  • No precision loss for any valid i32 or f32 value.
  • Runtime performance is nearly identical to using raw types, since the enum's size is just the size of the largest variant plus a tiny tag (which Rust optimizes where possible).

So unless you specifically don't care about type distinction or precision limits, sticking with the enum is the cleanest, safest solution in Rust.

内容的提问来源于stack exchange,提问作者anderspitman

火山引擎 最新活动