Structs in Rust Programming

Rust ProgrammingServer Side ProgrammingProgramming

Structs in Rust are user-defined data types. They contain fields that are used to define their particular instance.

We defined structs with the help of the struct keyword followed by the name we want for the struct. The name of the struct should describe the significance of the pieces of data that we are grouping together inside it.

Syntax

struct Employee {
   id: i32,
   name: String,
   leaves: i8,
}

The above syntax contains the name of the struct and inside the curly braces, we have different fields, namely, id which is of type i32, name and leaves.

Creating an Instance

To create an instance of the Employee struct, we do something like this:

fn main() {
   let emp1 = Employee {
      id : 10602,
      name : String::from("Mukul"),
      leaves : 9
   };
   println!("{:?}",emp1);
}

Output

Employee { id: 10602, name: "Mukul", leaves: 9 }

The above struct instance is not mutable; we can make it mutable by adding the mut keyword.

Example

 Live Demo

#![allow(unused)]
#[derive(Debug)]
struct Employee {
   id: i32,
   name: String,
   leaves: i8,
}
fn main() {
   let mut emp1 = Employee {
      id : 10602,
      name : String::from("Mukul"),
      leaves : 9
   };
   println!("{:?}",emp1);
   emp1.id = 10603;
   println!("{:?}",emp1);
}

Output

Employee { id: 10602, name: "Mukul", leaves: 9 }
Employee { id: 10603, name: "Mukul", leaves: 9 }

Unit Struct

We can also have a struct in Rust that doesn’t contain any fields. They are rarely useful but can be used in combination with other features.

Example

 Live Demo

#![allow(unused)]
#[derive(Debug)]
struct Person;
fn main() {
   let p = Person;
   println!("{:?}",p);
}

Output

Person

Tuple Structs

The third type of structs are known as tuple structs; they contain one or more comma-separated values.

Example

 Live Demo

#![allow(unused)]
#[derive(Debug)]
struct Color(u8, u8, u8);
fn main() {
   let white = Color(1, 1, 1);
   let Color(r, g, b) = white;
   println!("White = rgb({}, {}, {})", r, g, b);
}

Output

White = rgb(1, 1, 1)
raja
Published on 03-Apr-2021 13:32:03
Advertisements