Functions vs. Methods in Rust: What’s the Difference?

Anvar
2 min readOct 2, 2023

Rust is a cool language for writing computer programs. When you’re making things in Rust, you’ll meet two important ideas: functions and methods. They’re like tools you use when building stuff with Rust, but they work a bit differently. Let’s make it simple and see how they work with easy examples.

Functions in Rust

Functions are like little programs inside your bigger program. You give them some numbers or things to work with, and they give you back an answer. For example, imagine you want to add two numbers together:

fn add(a: i32, b: i32) -> i32 {
a + b
}

fn main() {
let result = add(5, 3);
println!("Sum: {}", result);
}

In this code, there’s a function called add. You tell it to add two numbers, and it does just that. The main part of your program calls this function and gets the sum.

Methods in Rust

Methods are like special powers that some things you make in Rust have. These powers are tied to those things. Let’s say you create a shape, like a rectangle, and you want it to be able to calculate its own area:

struct Rectangle {
width: u32,
height: u32,
}

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

fn main() {
let rect = Rectangle { width: 5, height: 3 };
let area = rect.area();
println!("Area: {}", area);
}

Here, our Rectangle has a special method called area. When you create a Rectangle, it knows how to calculate its own area. You just ask it, and it does the math for you.

So, What’s the Big Difference?

Now, let’s make it simple:

  • Functions are like separate little programs that can do stuff.
  • Methods are like special actions that certain things can do.

When do you use each one?

  • Use functions when you need to do something general that’s not tied to a specific thing you created.
  • Use methods when you want to define actions that are closely related to a specific type or structure you made.

Understanding these differences helps you write cleaner and more organized Rust code. Functions are your general tools, and methods are like superpowers for your custom-made things.

--

--

Anvar

Self-taught programmer, BSc CS student, avidly learning new programming languages and stacks. Join me on my coding journey!