Member-only story
Defining Struct
struct Car {
name: String,
door_count: u64
}
Instantiating Struct
let car1 = Car{
name: String::from("car1"),
door_count: 4
};// whole struct to mut, cannot mut only parts of the fields
let mut car2 = Car{
name: String::from("car2"),
door_count: 2
};
Accessing Struct’s Field
println!("{}", car1.name)
Struct Update Syntax
let car1 = Car{
name: String::from("car1"),
door_count: 4
};let car2 = Car{
name: String::from("car2"),
..car1 // base struct must always be the last field
};
Field Init Shorthand
fn build_car(name: String) -> Car {
Car {
name,
door_count: 4,
}
}
Tupple Struct
struct RGBColor(i32, i32, i32);
let black = RGBColor(0, 0, 0);
Unit-like Struct
struct SomethingWithOnlyTrait{}
Quirks — “lifetimes” to store references
// error[E0106]: missing lifetime specifier
struct Person {
name: &str
}fn main() {
let john = Person{name: "John"};
println!("{}", john.name);
}
Debugging Struct
fn main() {
let p = Person{ name…