Skip to content
Related Articles

Related Articles

Improve Article

Rust – Concept of Structures

  • Last Updated : 18 Jul, 2021
Geek Week

Structures are basically user-defined type mainly used for grouping different data types together. It overcomes the limitation of a traditional array that can only contain elements of the same data type. A structure can also contain a structure in itself. In Rust, structures are similar to tuples, but structure elements are easily accessible since they are named instead of indexed in the case of tuples.

In Rust, structures are of three types

  • Typical C like structure
  • Tuple struct: It is similar to a tuple, where the fields are un-named but with added functionalities.
  • Unit struct: These are field-less structures i.e. do not contain data. It is useful in cases where we just want to implement the trait on some type but don’t have data.

How to define a structure?

A structure is defined by struct keyword followed by the key-pair elements.

Rust




// typical c struct
struct Student{
name:String,
roll: u64,
dept: String,
}
  
// A unit struct
struct Unit;
  
// A tuple struct
struct Pair(i32, f32);

Here we have defined a Student structure using the struct keyword and its elements -“name”, “roll” and “dept”, along with their expected data types. We have also defined the unit struct and the tuple struct. When we defined the structure, no memory is allocated to it. Only when we will initialize it then it will be allocated.



Now, we will initialize our Student structure. Structure elements are accessed using the “.” (dot) operator.

Rust




#[derive(Debug)]
struct Student{
name:String,
roll: u64,
dept: String,
}
  
fn main() {
   let student1 = Student{
        name: String::from("Prem"),
        roll: 50,
        dept:String::from("CSE"),
    };
    println!("{:?}",student1.name);
}

Output:

"Prem"

Updating values of a defined structure

Since we want to update the value of a structure so the variable by which we are initializing it i.e. student1 in the above case should be declared mut (a variable that can be updated), otherwise by default it is immutable (can’t be updated). 

Rust




#[derive(Debug)]
struct Student{
name:String,
roll: u64,
dept: String,
}
  
fn main() {
   let mut student1 = Student{
        name: String::from("Prem"),
        roll: 50,
        dept:String::from("CSE"),
    };
  student1.roll=60;
    println!("{:?}",student1.roll);
}

Output:

60

Nested Structure

As earlier said, we can use a structure within another structure. Let us see.

Rust




#[derive(Debug)]
struct Addr{
  loc:String,
  pin:u64,
}
struct Student{
name:String,
roll: u64,
dept: String,
addr: Addr,
}
  
fn main() {
  let add1=Addr{
    loc: String::from("world"),
    pin:700001,
  };
   let student1 = Student{
        name: String::from("Prem"),
        roll: 50,
        dept:String::from("CSE"),
        addr:add1,
    };
    println!("{:?}",student1.addr.pin);
}

Output:

700001

Here we tried to add address structure into student structure. One thing to be noted is that the addr structure should be defined before the student structure and the same goes during initialization. Notice the method used to access the elements of a structure that is part of another structure. For this, we have used the dot operator twice as in student1.addr.pin.

Defining methods for a structure

Rust




#[derive(Debug)]
struct Triangle {
    base: f64,
    height: f64,
}
  
impl Triangle {
    fn area(&self) -> f64 {
        self.base * self.height * 0.5
    }
}
  
fn main() {
    let tri1 = Triangle {
        base: 3.0,
        height: 5.0,
    };
  
    println!("The area of the triangle is = {}",tri1.area());
}

Output:

The area of the triangle is = 7.5

We started an impl (implementation) block, within which we defined the method area for the triangle. We passed the address of the instance of the struct to the function and used self to refer to it.




My Personal Notes arrow_drop_up
Recommended Articles
Page :