Associated Functions
Part of the Object Oriented Programming section of Coddy's Rust journey — lesson 4 of 61.
Not all functions in an impl block need to operate on an existing instance. Functions that don't take self as a parameter are called associated functions—they're associated with the type itself rather than any particular instance.
The most common use for associated functions is creating constructors. By convention, these are often named new:
struct Player {
name: String,
score: u32,
}
impl Player {
fn new(name: String) -> Player {
Player {
name,
score: 0,
}
}
}
Notice there's no self parameter—this function doesn't need an existing Player to work. Instead, it creates and returns a brand new one. The return type is the struct itself.
To call an associated function, use the :: syntax with the type name instead of dot notation:
fn main() {
let player1 = Player::new(String::from("Alice"));
println!("{} starts with {} points", player1.name, player1.score);
// Output: Alice starts with 0 points
}
This pattern provides a clean way to initialize structs with default values or validation logic, keeping the creation logic bundled with the type definition. You've likely already seen this syntax with String::from()—that's an associated function too!
Challenge
EasyCreate a Book struct with two fields: title (String) and pages (u32).
Add an implementation block for Book with an associated function called new that:
- Takes a
title: Stringparameter - Returns a new
Bookwith the given title andpagesset to0
Also add a method called info that takes &self and returns a String in the format: "{title} has {pages} pages"
You will receive one input:
- The book's title (String)
Use the Book::new associated function to create a book with the provided title, then print the result of calling the info method.
Expected output format:
{title} has {pages} pagesCheat sheet
Functions in an impl block that don't take self as a parameter are called associated functions. They're associated with the type itself rather than any particular instance.
Associated functions are commonly used as constructors, typically named new:
struct Player {
name: String,
score: u32,
}
impl Player {
fn new(name: String) -> Player {
Player {
name,
score: 0,
}
}
}
To call an associated function, use the :: syntax with the type name:
let player1 = Player::new(String::from("Alice"));
String::from() is an example of an associated function you've already used.
Try it yourself
use std::io;
// TODO: Define the Book struct with title (String) and pages (u32) fields
// TODO: Add an impl block for Book with:
// - An associated function `new` that takes a title and returns a Book with pages set to 0
// - A method `info` that returns a String in the format "{title} has {pages} pages"
fn main() {
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Failed to read line");
let title = input.trim().to_string();
// TODO: Use Book::new to create a book with the provided title
// TODO: Print the result of calling the info method
}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