In Rust it seems it is possible to define a Enum with primitive types as representations:
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?
In some ways, an enum is similar to the boolean data type, which has true and false as its only possible values. However, boolean is a primitive type, while an enum is not.
Rust has two primitive compound types: tuples and arrays.
In Rust, methods cannot only be defined on structs, they can also be defined on tuples and enums, and even on built-in types like integers.
structs can be used to model cars and define state. methods and associated functions can be used to specify their behaviour. enums can be used to specify range of allowed values for a custom data type. traits can be used to describe shared behaviours across user-defined data types.
(This answer is as of 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. 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. This way, it's working more like C enums than C unions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With