Struct is a type you can create.
// unit struct
struct FileDirectory;
// tuple struct
#[derive(Debug)]
struct Color(u8, u8, u8);
// named struct
#[derive(Debug)]
struct Country {
population: u32,
capital: String,
leader_name: String
}
fn takes_file_directory(_input: FileDirectory) {
println!("haha");
}
fn main() {
let x = FileDirectory;
println!("{}", std::mem::size_of_val(&x));
let color = Color(20, 20, 100);
println!("{:?}", color);
let korea = Country {
population: 50_000_000,
capital: String::from("seoul"),
leader_name: String::from("Moon")
};
println!("{:#?}", korea);
}
Unit struct is an empty struct that is 0 byte. So if you need 0 size empty struct, you can use it.
Tuple struct is simply made with tuple style assignment. As we can see at Color struct, properties don't have name. We can approach to property by index(same as tuple - color.1
)
Named struct is what we the struct is. It has properties that have names, so we can assign and approach to them by their name.
Also we have to assign every properties when we make an instance of struct.
If we have variables same with property name of struct, we can write
let country = Country {
population,
capital,
leader_name
}
When you want to print(debug) the struct, we need to make #[derive(Debug)]
above the struct so we can do debug print with that struct.
We can use size_of_val(std::mem::size_of_val) function to check the size of struct. We can import that function to shorten it.
use std::mem::size_of_val;
And the size of struct is assigned by alignment. If we have 3bytes size struct, rust assign 3bytes for the struct. If we make it bigger 4bytes, it's size becomes 8bytes(make double of 4 -> 8 and 1byte of empty space).