Structures

Structures allow us to group variables of different data type into one single memory block. Variables present inside the structure are called fields of that structure. Each field has a datatype associated with it.

Structs in Rust come in three flavours.

1. Named Structs

They are similar to C structs. They are defined by using struct keyword followed by the name of the struct. Inside the struct, we define fields by specifying the name of the field and the data type of the field.

enum Genre {
    Pop,
    Electronic,
    Funk,
    Jazz,
    Metal,
}

struct Song {
    name : String,
    artist : String,
    duration : u8,
    genre : Genre,

}


fn main(){ 
    let s1 = {
        name : String::from("Blinding Lights"),
        artist : String::from("Weeknd"),
        duration : 262,
        genre : Genre::pop,
        };

    println!("Name of the song : {}",s1.name);

}

2.Tuple Structs

Tuple Structs don’t have a name associated with their fields, but we specify the data type of the fields.

struct Point(i32,i32,i32);
struct Rgb(i32,i32,i32);
struct Student(u8,u8,u8);


fn main(){
    let s = Student(95,93,85);
    let p  = Point(19,34,-23);
    let black = Rgb(0,0,0);

    println!(" X axis : {}",p.0);
    println!(" Red value : {}",black.0);

// tuple structs can also be destructured.

    let Student(physics,chemistry,biology) = s;
    println!("{}",physics);
    println!("{}",chemistry);
    println!("{}",biology);
}

Unit-like Structs

Unit-like structs don’t have any fields. They are defined by struct keyword followed by the name of the struct. They take 0 bytes of space. They can be useful when you need to implement a trait , but don’t store any data inside it.

struct Unit;

Associated Functions

Structs can have associated functions that are not tied to a specific instance of the struct. Associated functions are useful when creating new instances of a struct or performing some operation of the fields of the struct.

struct Marks {
    physics: u8,
    chemistry: u8,
    mathematics: u8,
}

impl Marks {
    fn new(physics: u8, chemistry: u8, mathematics: u8) -> Marks {
        Marks {
            physics,
            chemistry,
            mathematics,
        }
    }

    fn find_average(&self) -> u8 {
        (self.physics + self.chemistry + self.mathematics) / 3
    }
}

fn main() {
    let x = Marks::new(90, 75, 67);
    println!("{}", x.physics);
    println!("{}", x.chemistry);
    println!("{}", x.mathematics);
    let y = x.find_average();
    println!("Average : {}", y);
}