Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Primitive types in rust enums

Tags:

rust

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?

like image 630
maxaposteriori Avatar asked Jan 19 '14 09:01

maxaposteriori


People also ask

Are enums 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.

What are the primitive types in Rust?

Rust has two primitive compound types: tuples and arrays.

Can enums have methods Rust?

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.

What is difference between enum and struct in Rust?

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.


2 Answers

(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)
    }
}
like image 133
Corey Richardson Avatar answered Oct 23 '22 11:10

Corey Richardson


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.

like image 32
pepper_chico Avatar answered Oct 23 '22 12:10

pepper_chico