Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create 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: String parameter
  • Returns a new Book with the given title and pages set to 0

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} pages

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
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online Rust compiler