Accessing enumeration members

Given the possibility of the contents of a Rust enum, you may be thinking that accessing one of the members within the enumeration may not be the simplest of tasks. Thankfully, it is, as an enum variable is sometimes referred to as a scopable variable. For example, if we wanted to access members, we could use the following:

enum MyFirstEnum 
{ 
    TupleType(f32, i8, String), 
    StuctType {varone: i32, vartwo: f64}, 
    NewTypeTuple(i32), 
    SomeVarName 
} 
 
enum MySecondEnum 
{ 
    TupleType(f32, i8, String), 
    StuctType {varone: i32, vartwo: f64}, 
    NewTypeTuple(i32), 
} 
 
fn main()  
{ 
    let mut text1 = "".to_owned(); // text1: String 
    let mut text2 = "".to_owned(); // text2: String 
    let mut num1 = 0f32; 
     
    let value = MyFirstEnum::TupleType(3.14, 1, "Hello".to_owned()); 
    let value2 = MySecondEnum::TupleType(6.28, 0, "World".to_owned()); 
     
    if let MyFirstEnum::TupleType(f,i,s)  = value 
    { 
        text1 = s; 
        num1 = f; 
    } 
     
    if let MySecondEnum::TupleType(f,i,s) = value2 
    { 
        text2 = s; 
    } 
     
    println!("{} {} from the {} man", text1, text2, num1) 
} 
The code for this section is in the 07/enumscope folder, present in the supporting code bundle provided for this book.

The variables, value1 and value2, are scoped (uses ::) to MyFirstEnum and MySecondEnum respectively. When compiled, we will see the following output:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset