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. Useenum
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:
- Unit struct, they are without a body(unit meaning doesn't have anything)
struct FileDirectory;
- Tuple or Unnamed struct, it is unnamed because you don't have to add field names, you only need to add the types inside a tuple.
- They good for when you want a simple struct and care less about the field names.
- Each property can be accesses as in a tuple as well.
.0, .1
struct ColorRGB(u8,u8,u8);
fn main(){
let my_color = ColorRGB(205,298,100);
println!("I prefer the shade {}", my_color.1)
}
- Named struct, the popular struct. field names separated by commas are defined in a code block.
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)
}