Advanced

Structs and Methods

Create custom types with structs and attach behavior with methods.

What you will see

31

About 2 min of reading

Quick check

Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.

Try It

You will define a struct, attach methods, and call them through an instance.

1

I define a Person struct and create an instance, then print a field. The struct bundles fields into one named type.

struct Person { name: String, age: u32, } fn main() { let p = Person { name: "Ada".into(), age: 30 }; println!("{}", p.name); }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Ada
2

I print both fields together. Each field is accessed with dot notation through the instance.

struct Person { name: String, age: u32, } fn main() { let p = Person { name: "Ada".into(), age: 30 }; println!("{} {}", p.name, p.age); }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Ada 30
3

I add a method in an impl block that returns a greeting string. The &self gives the method access to the instance fields.

struct Person { name: String, } impl Person { fn greet(&self) -> String { format!("Hello, {}", self.name) } } fn main() { let p = Person { name: "Ada".into() }; println!("{}", p.greet()); }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Hello, Ada
4

I write a constructor function named new. The Self return type refers to the struct, and calling Person::new builds an instance.

struct Person { name: String, age: u32, } impl Person { fn new(name: &str, age: u32) -> Self { Person { name: name.into(), age } } } fn main() { let p = Person::new("Ada", 30); println!("{} {}", p.name, p.age); }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Ada 30
5

I mutate a field through a mutable instance. The &mut self method can change the instance it is called on.

struct Person { age: u32, } impl Person { fn have_birthday(&mut self) { self.age += 1; } } fn main() { let mut p = Person { age: 30 }; p.have_birthday(); println!("{}", p.age); }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
31

Data Flow

A struct holds fields; methods read or mutate through self.
1 Create a struct value
↓
2 Call a method with &self
↓
3 The method reads fields
↓
4 Return a computed value
Why this works
Impl blocks

Methods group into impl blocks:

impl Person {
    fn greet(&self) {}
    fn is_adult(&self) -> bool {
        self.age >= 18
    }
}

You can have multiple impl blocks for one struct. Fields are accessed with self.field inside methods.

The self reference

Methods receive self in three forms:

fn method(&self) {}       // borrow
fn method(&mut self) {}    // mutable borrow
fn method(self) {}         // consume

&self is the most common. It lets the method read the instance without taking ownership.

Examples

Defining a struct

Grouping fields

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

let p = Person { name: "Ada".into(), age: 30 };

A struct bundles related data. Fields must be given explicit types. .into() converts the string literal into a String.

Why it works: the struct defines a new named type.

Writing a method

Attaching behavior

impl Person {
    fn greet(&self) -> String {
        format!("Hello, {}", self.name)
    }
}

println!("{}", p.greet());

Methods live in an impl block. &self is a reference to the instance. Inside, self.name accesses fields.

Why it works: impl attaches functions to a type without modifying the struct definition.

Constructors

Building instances

impl Person {
    fn new(name: &str, age: u32) -> Self {
        Person { name: name.into(), age }
    }
}

let p = Person::new("Ada", 30);

A new function is a conventional constructor. Self refers to the type in the impl block. Person::new calls it.

Why it works: :: accesses associated functions on the type.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Ownership Basics
Previous Lesson
Ownership Basics
Next Lesson
Traits
Traits →