Structures In Rust

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.
In general, If we take an example of length and breadth in case of the area of many of 2D shapes then we calculate the area using the length and breadth as fields so we can create a structure named Area with length and breadth as fields. such as:

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:



Written by 

Ayush Aggarwal is a Software Consultant having experience of more than 11 months. He has knowledge of various programming languages such as JAVA, C and C++, and also has good knowledge of database technologies like MySQL. He has worked upon Object Oriented Paradigm and a Java and Android enthusiast. His hobbies include playing football, basketball etc.

Knoldus Pune Careers - Hiring Freshers

Get a head start on your career at Knoldus. Join us!