Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing tuple from within an enum

Tags:

rust

I have a Rust enum defined like this

enum MyFirstEnum {
    TupleType(f32, i8, String),
    StuctType {varone: i32, vartwo: f64},
    NewTypeTuple(i32),
    SomeVarName
}

I have the following code:

let mfe: MyFirstEnum = MyFirstEnum::TupleType(3.14, 1, "Hello".to_string());

I'm following the Rust documentation and this looks fine. I don't need to define everything in the enum, but how would I go about accessing the mid element in the enum tuple?

mfe.TupleType.1 and mfe.1 don't work when I add them to a println!

I know Rust provides the facility to do pattern matching to obtain the value, but if I changed the code to define the other variants within the enum, the code to output a particular variant would quickly become a mess.

Is there a simple way to output the variant of the tuple (or any other variant) in the enum?

like image 523
Nodoid Avatar asked May 30 '16 01:05

Nodoid


1 Answers

This is a common misconception: enum variants are not their own types (at least in Rust 1.9). Therefore when you create a variable like this:

let value = MyFirstEnum::TupleType(3.14, 1, "Hello".to_string());

The fact that it's a specific variant is immediately "lost". You will need to pattern match to prevent accessing the enum as the wrong variant. You may prefer to use an if let statement instead of a match:

if let MyFirstEnum::TupleType(f, i, s) = value {
     // Values available here
     println!("f: {:?}", f);
}
like image 189
Shepmaster Avatar answered Nov 04 '22 10:11

Shepmaster