Rust Learning Plan – Day 6: Structs and Methods

Day 6: Structs and Methods (struct & impl)Today, we will give your code some “shape” and “behavior”—Rust’s structs and methods are similar to Python’s classes, but lighter and more rigorous.

Day 6 Learning Plan (Approx. 1–2 hours)

Learning Objectives

  • • Define and use structs (<span>struct</span>)
  • • Implement methods (<span>impl</span> block)
  • • Understand the relationship between field mutability and lifetimes
  • • Write a complete struct program with methods

1. Defining Structs (30 minutes)

A struct (struct) is a custom data type:

struct User {
    username: String,
    email: String,
    active: bool,
}

fn main() {
    let mut user1 = User {
        username: String::from("alice"),
        email: String::from("[email protected]"),
        active: true,
    };

    println!("Username: {}", user1.username);

    user1.email = String::from("[email protected]");
    println!("Updated email: {}", user1.email);
}

Rust does not have a default “class”, but struct + impl can achieve the same object-oriented effect.

2. Shortened Syntax and Struct Update (10 minutes)

When the variable name and field name are the same, you can shorten it:

fn build_user(username: String, email: String) -> User {
    User {
        username,
        email,
        active: true,
    }
}

Struct update syntax:

let user2 = User {
    email: String::from("[email protected]"),
    ..user1 // Reuse the remaining fields of user1
};

Note: Moved fields (like String) will make part of user1 invalid.

3. Tuple Structs and Unit Structs (10 minutes)

struct Color(i32, i32, i32);
let black = Color(0, 0, 0);

struct AlwaysEqual;
let _x = AlwaysEqual;

Tuple structs are suitable for lightweight encapsulation, while unit structs are often used to implement traits.

4. Implementing Methods for Structs (30 minutes)

<span>impl</span> blocks define methods:

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn can_hold(&self, other: &Rectangle) -> bool {
        self.width &gt;= other.width && self.height &gt;= other.height
    }
}

fn main() {
    let rect1 = Rectangle { width: 30, height: 50 };
    let rect2 = Rectangle { width: 10, height: 40 };

    println!("Area: {}", rect1.area());
    println!("Can it hold another rectangle? {}", rect1.can_hold(&rect2));
}
  • <span>&self</span> is similar to Python’s <span>self</span>, but explicitly declares a reference.
  • <span>impl</span> blocks can have multiple instances.
  • • Static methods are written as <span>fn new(...) -> Self</span>.

5. Today’s Practice (20 minutes)

Write a struct and implement methods:

struct Circle {
    radius: f64,
}

impl Circle {
    fn area(&self) -> f64 {
        std::f64::consts::PI * self.radius * self.radius
    }

    fn new(radius: f64) -> Self {
        Circle { radius }
    }
}

fn main() {
    let c = Circle::new(3.0);
    println!("The area of a circle with radius {:.1} = {:.3}", c.radius, c.area());
}

Also write a function to calculate the average area of multiple Circles.

Day 6 Summary

  • struct = Data Structure
  • impl = Collection of Behaviors
  • • Rust ensures data safety within structs through ownership and references.At this point, you can encapsulate logic and data, which is the starting point for building complex systems.

Next, we will enter Day 7: Enums (enum) and Pattern Matching (match), which is another powerful expression in Rust—a type-safe version of switch.

Leave a Comment