[英]Primitive types in rust enums
In Rust it seems it is possible to define a Enum with primitive types as representations: 在Rust中,似乎可以使用基本类型定义Enum作为表示:
enum A {
f64,
i32
}
How can I use such an enum? 我该如何使用这样的枚举? For example, how would I create an instance and how would I use a match statement to handle different primitive types? 例如,如何创建实例以及如何使用match语句处理不同的基元类型?
(This answer is as of 0.9) (这个答案是从0.9开始)
That isn't doing quite what you think it is doing. 这并不是你认为它正在做的事情。 It's creating an enum A
with variants named f64
and i32
, not using those types. 它正在使用名为 f64
和i32
变体创建枚举A
,而不是使用这些类型。 Since types and everything else (variables etc) share different namespaces, you might not notice. 由于类型和其他所有内容(变量等)共享不同的命名空间,您可能不会注意到。 An example of using the original enum: 使用原始枚举的示例:
enum A {
f64,
i32
}
fn main() {
let x: A = f64;
let y: A = i32;
match x {
f64 => println!("got f64"),
i32 => println!("got i32")
}
}
To actually wrap values of those types, you need to use "tuple-like variants": 要实际包装这些类型的值 ,您需要使用“类似于元组的变体”:
enum A {
Float(f64),
Int(i32)
}
fn main() {
let x: A = Float(42.0);
let y: A = Int(7);
match x {
Float(value) => println!("got Float({})", value),
Int(value) => println!("got Int({})", value)
}
}
You're not doing what you expect, check the output of this: 你没有做你期望的,检查输出:
enum A {
f64,
i32
}
fn main() {
let x:A = f64;
let y:A = i32;
println!("{}, {}", x as int, y as int);
}
f64
and i32
as just variants of the enum, just like any other name for a constant. f64
和i32
只是枚举的变体,就像常量的任何其他名称一样。 This way, it's working more like C enums than C unions. 这样,它的工作方式更像是C enums而不是C联合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.