Coding/Learn/rust/structs and methods
Rust Foundational Course
01.Introduction to Rust & Memory Safety
02.Formatting, Comments & Macros (println!)
03.Variables, Mutability & Shadowing
04.Scalar & Compound Types (Integers, Floats, Tuples, Arrays)
05.Functions, Parameters & Return Expressions
06.Conditionals & If as an Expression
07.Ownership Rules & Move Semantics
08.References & Borrowing (&T)
09.Mutable References (&mut) & Aliasing XOR Mutability
10.Slices & String Types (&str vs String)
11.Loops in Rust (loop, while, for)
12.Pattern Matching with match Expressions
13.Structs, Associated Functions & Methods (impl)
14.Enums & the Option<T> Type (No Null!)
15.Concise Pattern Matching (if let & let else)
16.Vectors & Growable Collections (Vec<T>)
17.Error Handling with Result<T, E> & the ? Operator
18.Traits, Shared Behavior & Generics
19.Closures & Functional Iterators (map, filter, collect)
20.Capstone: High-Performance In-Memory Log Telemetry Engine
Course Certificate0%

Complete all lessons to earn

LearnStructs, Associated Functions & Methods (impl)
13 / 20 0%
Lesson 13 of 20
6 mins read

Structs, Associated Functions & Methods (impl)

PreviousNext Lesson
In Plain English

Structs allow you to name and package multiple related values into a cohesive custom type. Methods are defined inside impl blocks and take &self as their first parameter, while associated functions (like Self::new) act as constructors without &self.

The Mental Model

"A struct is like an architect’s blueprint for a house specifying dimensions and materials. An impl block is the user manual explaining what that house can do (like house.turn_on_lights())."

Deep Dive: How It Works

Struct Definition: struct User { username: String, active: bool }

Methods with &self: Borrow the struct instance immutably to read its fields.

Associated Functions (Self::new): Functions associated with the type but not an instance (called with Type::function()).

Syntax Blueprint

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

Define methods inside impl blocks with &self to access fields.

PointCore Rules to Remember

Point star
Custom Types: Groups heterogeneous fields under a meaningful domain name.
Point star
&self Borrowing: Methods borrow the instance without consuming ownership.
Point star
Constructors: Idiomatic Type::new(...) associated functions build instances cleanly.

Common Beginner Traps & How to Fix Them

Mistake:Forgetting &self in method signatures.

Why it happens: Writing fn area(self) consumes ownership of the instance, preventing you from using it again.

How to fix: Use &self for read-only methods and &mut self for mutating methods.

Pro Tip: Add #[derive(Debug)] above your struct to enable automatic {:?} debug formatting support.

Live Interactive Example

Hit Run Code to see it live
Rectangle Struct with Methods
Rust 1.78 / rustc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Output Console
Click "Run Code" to view the rendered output.
How it works: Demonstrates struct instantiation via associated function and calling &self method.

Your Turn: Micro Challenge

No pressure! Edit the starter code below and test your solution with instant feedback.

Micro Exercise

Implement a BankAccount struct

  • PointCreate struct BankAccount { balance: i32 }
  • PointImplement impl BankAccount with fn new(balance: i32) -> Self { Self { balance } } and fn get_balance(&self) -> i32 { self.balance }
  • PointIn main(), let acc = BankAccount::new(500); print "Account Balance: $500".
1
2
3
4
5
6
7
Sandbox Output
Click "Run & Check" to test your solution.

Finished reading and practicing?

Mark this lesson as completed to update your course progress.

PreviousNext Lesson
Overview100 SheetLearnCertificates