The Self Parameter
Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 2 of 61.
When a method needs to access the data stored in a struct instance, it uses the &self parameter. This special parameter is always the first argument in a method and represents a reference to the instance the method is called on.
The & symbol means we're borrowing the instance rather than taking ownership of it. This allows the method to read the struct's fields without consuming the instance:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn is_square(&self) -> bool {
self.width == self.height
}
}
Inside the method body, self gives you access to all the struct's fields using dot notation. The area method reads both width and height to calculate and return the result.
Because &self only borrows the instance, you can call multiple methods on the same struct without any issues:
fn main() {
let rect = Rectangle { width: 10, height: 5 };
println!("Area: {}", rect.area()); // 50
println!("Square? {}", rect.is_square()); // false
}
Methods using &self are read-only—they can examine the struct's data but cannot change it. In the next lesson, you'll learn how to create methods that can modify the instance.
Challenge
EasyCreate a Circle struct with a single field: radius (f64).
Add an implementation block for Circle with two methods that use &self:
circumference— returns the circumference asf64(formula:2.0 * 3.14159 * radius)diameter— returns the diameter asf64(formula:2.0 * radius)
You will receive one input:
- The circle's radius (f64)
Create a Circle instance with the provided radius, then print the circumference and diameter on separate lines.
Expected output format:
{circumference}
{diameter}Cheat sheet
Methods access struct data using the &self parameter, which must be the first argument. The & symbol means the method borrows the instance rather than taking ownership:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
fn is_square(&self) -> bool {
self.width == self.height
}
}
Inside the method, use self with dot notation to access struct fields. Methods with &self are read-only and can examine data but not modify it.
Because &self only borrows the instance, you can call multiple methods on the same struct:
let rect = Rectangle { width: 10, height: 5 };
println!("Area: {}", rect.area()); // 50
println!("Square? {}", rect.is_square()); // false
Try it yourself
use std::io;
// TODO: Define the Circle struct here
// TODO: Add the implementation block for Circle with circumference and diameter methods
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
let radius: f64 = input.trim().parse().expect("Invalid number");
// TODO: Create a Circle instance and print the circumference and diameter
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Methods and Behavior
Intro Implementation BlocksThe Self ParameterMutable MethodsAssociated FunctionsMultiple Implementation BlocksMethod ChainingRecap - Rectangle Actions4Project: Virtual Pet
Defining the PetFeeding the Pet7Standard Traits
The Debug TraitThe Display TraitClone and CopyEquality TraitsRecap - Printable Point10Project: Document System
The Draw TraitText Component2Encapsulation and Modules
Modules BasicsThe Public KeywordPrivate FieldsGettersSettersRecap - Secure Locker5Generics
Generic StructsGeneric MethodsMultiple Generic TypesGeneric FunctionsRecap - Coordinate Point8Traits as Bounds
Trait Bounds SyntaxMultiple BoundsThe Where ClauseReturning Types with TraitsRecap - Generic Printer11Design Patterns in Rust
Newtype PatternCompositionThe Drop TraitFrom and IntoRecap - Smart Pointer Mock