struct User {
username: String,
email: String,
sign_in_count: u64,
active: bool,
}
pub fn struct_def() {
let user = User {
email: String::from("someone@example.com"),
username: String::from("someusername123"),
active: true,
sign_in_count: 1,
};
let mut user2 = User {
email: String::from("sometwo@example.com"),
..user
};
user2.active = false;
let user3 = struct_build_user(String::from("some3"), String::from("some3@example.com"));
}
fn struct_build_user(username: String, email: String) -> User {
User {
username,
email,
active: true,
sign_in_count: 1,
}
}
#[derive(Debug)]
struct Color(i32, i32, i32);
#[derive(Debug)]
struct Point(i32, i32, i32);
pub fn tuple_struct() {
let black = Color(0, 0, 0);
println!("{:#?}", black);
let origin = Point(0, 0, 0);
println!("{:#?}", origin);
}
struct AlwaysEqual;
fn struct_no_field() {
let subject = AlwaysEqual;
}
#[derive(Debug)]
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
impl Rectangle {
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
}
pub fn struct_method() {
let rect1 = Rectangle {
width: dbg!(30),
height: 50,
};
dbg!(&rect1);
println!(
"The area of the rectangle is {} square pixels.",
rect1.area()
);
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
}