Structures In Rust

Sugandha Arora
Sep 3, 2018 · 3 min read

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:

let length = 0; let breadth = 0;

Then struct allow us to combine these two into a single, i.e. Area

struct Area{ length: i32, breadth: i32, }

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.

#[derive(Debug)] struct Person { name: &'a str, age: u8, } // A unit struct struct Nil; // A tuple struct struct Pair(i32, f32); // A struct with two fields struct Point { x: f32, y: f32, } // Structs can be reused as fields of another struct #[allow(dead_code)] struct Rectangle { p1: Point, p2: Point, } fn main() { // Create struct with field init shorthand let name = "Peter"; let age = 27; let peter = Person { name, age }; // Print debug struct println!("{:?}", peter); // Instantiate a `Point` let point: Point = Point { x: 0.3, y: 0.4 }; // Access the fields of the point println!("point coordinates: ({}, {})", point.x, point.y); // Make a new point by using struct update syntax to use // the fields of our other one let new_point = Point { y: 1.0, ..point }; // `new_point.y` will be the same as `point.y` because we used // that field from `point` println!("second point: ({}, {})", new_point.x, new_point.y); // Destructure the point using a `let` binding let Point { x: my_x, y: my_y } = point; let _rectangle = Rectangle { // struct instantiation is an expression too p1: Point { x: my_y, y: my_x }, p2: point, }; // Instantiate a unit struct let _nil = Nil; // Instantiate a tuple struct let pair = Pair(1, 0.1); // Access the fields of a tuple struct println!("pair contains {:?} and {:?}", pair.0, pair.1); // Destructure a tuple struct let Pair(integer, decimal) = pair; println!("pair contains {:?} and {:?}", integer, decimal); }

We can run Rust code by clicking here. And the output to the above code is:

Person { name: "Peter", age: 27 } point coordinates: (0.3, 0.4) second point: (0.3, 1) pair contains 1 and 0.1 pair contains 1 and 0.1

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:

struct Area(i32, i32, i32); // You can reference the elements using index but not name let area = Area(10,20,30) println!("Area parameters are {},{},{}", area.0, area.1, area.2); // Where the Tuple Struct is useful struct Inches(i32); let length = Inches(10); // destructure to get the value let Inches(integer_length) = length; println!("length is {} inches", integer_length);

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:

struct Area; let x = Area;

References:

https://doc.rust-lang.org/1.9.0/book/
https://doc.rust-lang.org/stable/rust-by-example/


Originally published at blog.knoldus.com on September 3, 2018.

Sugandha Arora

Written by

Knoldus - Technical Insights

Knols, Insights and Opinions from the curious minds at Knoldus Inc.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade