title | slug | excerpt | date | author |
---|---|---|---|---|
Struct in Rust |
struct-in-rust |
Explain the struct in Rust. Rectangle is used to demonstrate the behaviour of the struct. |
09.10.23 |
Nayantha Yasiru |
Rectangle is used to Demonstrate
#[derive(Debug)] can be used to easily print struct on the output / CMD.
{:?} - list all the values in single line
{:#?} - format the struct (similar to json format)
struct Rectangle {
width: u32, // fields
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 { // self is calling itself
self.width * self.height
}
fn can_hold(&self, rect: &Rectangle) -> bool {
self.area() >= rect.area() && (
(self.width >= rect.width && self.height >= rect.height) ||
(self.width >= rect.height && self.height >= rect.width)
)
}
fn make_square(size: u32) -> Rectangle { // associated method - not calling self method
Rectangle { width: size, height: size }
}
}
Struct Construct
Normal
fn build_user(email: String, username: String) -> User {
User {
email: email,
username: username,
active: true,
sign_in_count: 1,
}
}
Simple & Fast Way
fn build_user(email: String, username: String) -> User {
User {
email,
username,
active: true,
sign_in_count: 1,
}
}
Constuct from another struct - Normal
let user2 = User {
email: String::from("[email protected]"),
username: String::from("anotherusername567"),
active: user1.active,
sign_in_count: user1.sign_in_count,
};
Simple & Fast Way
let user2 = User {
email: String::from("[email protected]"),
username: String::from("anotherusername567"),
..user1
};