Structures are used to creating a more complex data structure. Basically, we have three types of Structures in Rust:
- The classic C Structs
- Tuple structs, which are, basically, named tuples.
- Unit structs, which are field-less, are useful for generics.
Then struct allow us to combine these two into a single, i.e. Area
When we are creating a struct, the values in the struct are immutable by default, like other bindings in Rust. Now we will have a look at how to use this Struct and use the values from the struct. And also we can make a new Area by using struct update syntax to use the fields of our other one.
We can run Rust code by clicking here. And the output to the above code is:
Now We have Tuple struct, Rust has another data type that’s like a hybrid between a tuple and a struct, called a ‘tuple struct’. Tuple structs have a name, but their fields don’t. It is almost always better to use a
struct than a tuple struct, but there is one use case where tuple struct is particularly useful and that is if it has only one value. It lets us define a new type that is distinct from its contained value and also expresses its own semantic meaning:
And we also have unit-like structs, we can have the structs with no member. It is said to be unit-like as it resembles with the empty tuple (). It is usually not useful but sometimes we can use it as a Marker Type e.g we can define a particular event or flag. We can create the unit-like struct as: