ðïļ Rust Structs & Methods
ðĶ Define a Struct
ð§ą Create an Instance
ð§ Access Fields
You can use dot syntax like
user.age
.
ð ïļ Define Methods with impl
impl Person {
// Method with &self
fn greet(&self) {
println!("Hi, I'm {}!", self.name);
}
// Method that returns a value
fn is_adult(&self) -> bool {
self.age >= 18
}
// Associated function (like static)
fn new(name: &str, age: u8) -> Self {
Person {
name: name.to_string(),
age,
}
}
}
ðĻ Use Methods
ðŊ Mutable Method with &mut self
ð§ą Tuple Structs
ðŠķ Unit Structs
Used when you just want a type without data.
Example
struct JsonSerializer;
trait Serializer {
fn serialize(&self, data: &str) -> String;
}
impl Serializer for JsonSerializer {
fn serialize(&self, data: &str) -> String {
format!("{{\"data\": \"{}\"}}", data)
}
}
Usage:
ð§Ž Struct Update Syntax
let person1 = Person {
name: String::from("Alice"),
age: 25,
};
let person2 = Person {
name: String::from("Bob"),
..person1
};
Moves fields from
person1
. Only works with non-borrowed types or if fields implementClone
.