Menu
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL SQLITE MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING HTML & CSS BASH RUST DART PLAYWRIGHT TOOLS MATH SHEETS POWER BI

Rust Methods


Share

Methods

In the Structs chapter, you used a struct to group related data, like the name and age of a person.

Often, you also want functions that work with that data, for example a function that prints a greeting, or checks if the person can vote. A function that belongs to a struct is called a method.

Methods are written inside an impl block (short for implementation), after the struct:

Example

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

impl Person {
  fn greet(&self) {
    println!("Hello, my name is {} and I am {} years old.", self.name, self.age);
  }
}

fn main() {
  let user = Person {
    name: String::from("John"),
    age: 35,
  };

  user.greet();
}
Try it Yourself »

Example explained:

  • impl Person starts a block with methods for the Person struct
  • fn greet(&self) creates a method called greet. The first parameter, &self, is the object that the method is called on
  • Inside the method, self.name and self.age read the fields of that object
  • user.greet() calls the method with dot syntax, just like you access a field

The & in &self means that the method borrows the object. It can read the fields, but it does not take ownership, so you can still use user after the call.


Methods That Return a Value

Just like other functions, a method can return a value. Use -> followed by the type of the value:

Example

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

let user = Person {
  name: String::from("Liam"),
  age: 16,
};

println!("Can {} vote? {}", user.name, user.can_vote());
Try it Yourself »

Liam is 16, so can_vote() returns false.


Change Fields With &mut self

To change the fields of an object, the method must use &mut self instead of &self:

Example

impl Person {
  fn have_birthday(&mut self) {
    self.age += 1;
  }
}

let mut user = Person {
  name: String::from("Jenny"),
  age: 29,
};

user.have_birthday();
println!("{} is now {} years old.", user.name, user.age);
Try it Yourself »

The object must also be mutable (let mut). If you forget mut, the code will not compile:

Example

let user = Person {
  name: String::from("Jenny"),
  age: 29,
};

user.have_birthday(); // Error
Try it Yourself »


Associated Functions

All functions inside an impl block are called associated functions, because they belong to the struct. A function that does not have self as its first parameter is not a method, because it is not called on an object.

A common example is a function called new(), which creates a new object. You call it with the struct name and ::, just like String::from():

Example

impl Person {
  fn new(name: &str, age: u32) -> Person {
    Person {
      name: String::from(name),
      age: age,
    }
  }
}

let user = Person::new("John", 35);
println!("{} is {} years old.", user.name, user.age);
Try it Yourself »

Note: Rust does not have special constructors like some other languages. new is just a normal name that Rust programmers use for functions that create an object.


Putting It Together

An impl block can have many methods. Here, a player starts with 0 points, gets points two times, and then shows the score:

Example

struct Player {
  name: String,
  score: u32,
}

impl Player {
  fn new(name: &str) -> Player {
    Player {
      name: String::from(name),
      score: 0,
    }
  }

  fn add_points(&mut self, points: u32) {
    self.score += points;
  }

  fn show(&self) {
    println!("{} has {} points", self.name, self.score);
  }
}

fn main() {
  let mut player = Player::new("Jenny");
  player.add_points(10);
  player.add_points(5);
  player.show();
}
Try it Yourself »

Summary

First parameter What it can do How to call it
&self Read the fields user.greet()
&mut self Read and change the fields (the object must be mut) user.have_birthday()
No self Associated function, often used to create an object Person::new("John", 35)


Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by W3Schools. All Rights Reserved. W3Schools is Powered by W3.CSS.