What Are Methods?
Methods in Rust are functions linked to a specific data type. They offer a natural, organized way to operate on instances of that type. To define a method, use theimpl keyword followed by the name of the struct and enclose the method definitions within curly braces. Below is an example of a basic method definition:
&self is shorthand for self: &Self, representing a reference to the instance on which the method is called.
Example: Defining Methods for a Book Struct
Consider aBook struct with fields for a title and a number of pages. We will define various methods to calculate reading time (assuming one page per minute), compare the page count between books, and create a default book instance.
&self because they act on an instance of Book. The function default_book does not take self as a parameter, which is why it’s called an associated function and is invoked using the :: syntax.
Using the Book Methods in main()
Here is an example showing how to createBook instances and call the defined methods:
This example demonstrates how methods encapsulate behavior within a struct, enhancing code readability and reusability.
Calling Methods with Dot Notation
Rust allows you to call methods on struct instances using dot notation. For instance, to calculate the reading time for a book, you simply call the method on the instance:reading_time method to determine the reading duration based on the page count.
Mutable Methods
When a method needs to modify the instance it is called on, it takes&mut self as a parameter. Consider the following example where the set_title method updates the book’s title:
set_title method uses a mutable reference (&mut self) to modify the title field. In the main function, note that book1 must be declared as mutable (mut) to allow this modification.
Implementing the Display Trait
Implementing theDisplay trait for a custom struct enables formatted output using the {} placeholder. The following is an example using a Point struct:
fmt method defines custom formatting for Point. The println! macro then uses this implementation to display the point in the desired format.
Implementing traits like
Display not only improves output readability but also enhances the overall flexibility of your custom types.Summary
- Methods in Rust are defined within an
implblock linked to a specific type. - Functions that require access to an instance use
&self, while functions withoutselfare associated functions called with the::syntax. - Mutable methods require the use of
&mut selfto indicate that the instance can be modified. - The
Displaytrait can be implemented for custom formatting, making your types more versatile in formatted output.