Tuple structs – the hybrid of two

Consider a struct with three fields. It will have a name for the struct type and the three fields with their types:

struct Test 
{ 
     drink: bool, 
     number: i32, 
     price: f32 
} 

Let's consider what this actually is and if we can we not rewrite this as follows:

let Test: (bool, i32, f32) = (false, 4, 1.55); 

Well, we can, but we will now run into how to access the members of the tuple. We will also run into assigning one tuple to another. You can't really define two structs, which are identical in everything other than the struct type name, and then assign the second struct type to the first.

To get around this, Rust has the tuple struct hybrid. It contains the struct type but then assigns the fields as a tuple:

struct TestOne (f32, i8, &str); 
struct TestTwo (f32, i8, &str); 

We now have the flexibility of a tuple, but with the protection of the struct. Despite the arity being the same and the types inside the struct being the same, they are different types.

As with a regular tuple, we can access the members of the tuple struct in the same way:

let i = TestOne.1; 
..................Content has been hidden....................

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