<ao> | Adetunji's Blog

Struct and Enum

struct and enum are alike but use differently, a struct is used when you want to group things together and an enum when you have choices and will likely select one at a time.

Use struct when you want one thing and another thing. Use enum when you want one thing or another thing.

struct

Short form for Structure are created with the keyword struct and by convention named with UpperCamelCase words.

There are 3 types of struct:

struct FileDirectory;
struct ColorRGB(u8,u8,u8);

fn main(){
	let my_color = ColorRGB(205,298,100);
	println!("I prefer the shade {}", my_color.1)
}
struct Country{
    population: u32,
    capital: String,
    leader_name: String,
}

Enum

enum are created with the enum keyword and choices are made with double colon(::) followed by the name of the variant.

enum Gender{
    Male,
    Female,
    Others,
}

struct Person {
    name: String,
    age: i8,
    gender: Gender,
}

fn main(){
    let adetunji = Person{   					 
        name: String::from("Adetunji"),
	age: 29,
	gender: Gender::Male,
    };
    println!("{}", adetunji.name)
}

#note #rust