1 KiB
1 KiB
Struct.
Types.
Classic.
struct ColorClassicStruct {
red: i32,
green: i32,
blue: i32,
}
let mut green = ColorClassicStruct {
red: 0,
green: 255,
blue: 0,
}
green.red = green.blue;
Tuple.
Have no field names.
struct Point(i32, i32, i32);
let x = Point(0, 0, 0);
Unit-like.
Have nothing. TODO: add use-cases.
struct AlwaysEqual;
let subject = AlwaysEqual;
Shortcuts.
Field-init.
Copy values with the same name.
fn create_color(red: i32, green: i32, blue: i32) -> ColorClassicStruct {
ColorClassicStruct {
red,
green,
blue,
}
}
Struct update.
Copy the rest of the struct.
let color2 = ColorClassicStruct {
red: 255,
..color1
};
Logic.
You can write logic in structs.
struct Package {
sender_country: String,
recipient_country: String,
fee: u32
}
impl Package {
fn is_international(&self) -> bool {
self.sender_country != self.recipient_country
}
}