Skip to content

🏗ïļ Rust Structs & Methods


ðŸ“Ķ Define a Struct

struct Person {
    name: String,
    age: u8,
}

ðŸ§ą Create an Instance

let user = Person {
    name: String::from("Alice"),
    age: 30,
};

🧠 Access Fields

println!("{} is {} years old", user.name, user.age);

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

let alice = Person::new("Alice", 30);
alice.greet();
println!("Is adult? {}", alice.is_adult());

ðŸŽŊ Mutable Method with &mut self

impl Person {
    fn have_birthday(&mut self) {
        self.age += 1;
    }
}
let mut bob = Person::new("Bob", 25);
bob.have_birthday();

ðŸ§ą Tuple Structs

struct Color(u8, u8, u8);

let red = Color(255, 0, 0);
println!("R: {}", red.0);

ðŸŠķ Unit Structs

struct Marker;

let m = Marker;

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:

let serializer = JsonSerializer;
println!("{}", serializer.serialize("hello"));

🧎 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 implement Clone.


📌 Derive Debug & Traits

#[derive(Debug, Clone, Copy)]
struct Point {
    x: i32,
    y: i32,
}
let p = Point { x: 3, y: 4 };
println!("{:?}", p);