Struct
And some
Debugtrait is useful for printing.Defaulttrait is useful to initializtion.
Example
main.rs
#[derive(Debug)]
struct Person {
name: String,
age: u32,
}
impl Default for Person {
fn default() -> Self {
Person {
name: String::from("Anonymous"),
age: 20,
}
}
}
#[derive(Debug, Default)]
struct Position {
x: f32,
y: f32,
}
fn main() {
let p = Person {
age: 25,
..Default::default()
};
println!("{:?}", p);
println!("Pretty print: {:#?}", p);
println!("Hello, this is {} {}!", p.name, p.age);
let position = Position {
..std::default::Default::default()
};
println!("{:?}, {:?}", position.x, position.y)
}
#[derive(Debug)]
struct Person {
name: String,
age: u32,
}
let p = Person { age: 20, ..Default::default() };
let user = User {
name: String::from("Joe"),
age: 20,
};
// Field init shorthand
let name = String::from("Joe");
let user2 = User {
name,
age: 20,
};
// Struct update syntax
let user3 = User {
..user2
}
// Tuple structs
struct Color(u8, u8, u8);
let black = Color(0, 0, 0);
Method systax: Rust has feature called ==automatic referencing and dereferencing==. Like Go, the compiler knows the types, and can dereference if necessary, don't need to use -> . like Clang.
struct Rect {
width: u32,
height: u32,
}
impl Rect {
fn area(&self) -> u32 {
self.width * self.height
}
}