Adding Functionality with Methods
Adding Functionality with Methods
Hello! In this lesson, we will explore how to add functionality to your structs using methods in Rust. Just as you use functions to encapsulate behavior in your programs, methods allow you to encapsulate behavior within a struct. This lesson will cover defining methods, creating constructors, and using mutable methods to add functionality to structs.
Let's get started!
What are Methods?
Methods in Rust are similar to functions, but they are associated with an instance of a struct and can operate on its data. Think of methods as actions that instances of structs can perform. Let's use a Rectangle struct as an analogy to understand this concept better.
Imagine we have a Rectangle struct, and we want this rectangle to perform certain actions, such as calculating its area or changing its dimensions. Methods allow us to define these actions directly so the rectangle "knows" how to perform these actions on its own.
Defining Methods for Structs
In Rust, methods are defined within an impl block, connecting them to a specific struct. This enables us to associate behavior with the struct. The first parameter of a method must always be &self. The self keyword refers to the instance of the struct. We use & to prevent the method from taking ownership of the instance. After defining a method, call it using dot syntax on the desired instance of the struct. The instance of the struct automatically gets passed as the self parameter. Let's take a look:
In this example:
- We defined a struct named
Rectanglewith two fields:widthandheight, both of typef32. - Inside the
implblock, we defined a methodareathat borrows the instance of the struct using&self. This method calculates and returns the area of the rectangle. - We then created an instance of
Rectangle, calledrect - We use
rect.area()to call theareamethod.rectautomatically gets passed as theselfparameter.
