Methods are similar to functions: we declare them with the fn
keyword and a name, they can have parameters and a return value, and they contain some code that’s run when the method is called from somewhere else. Methods are defined within an impl
(implementation) block, and they can either be associated functions (called with the ::
syntax) or instance methods (called with the .
syntax).
Here is how you define and call a method:
struct Rectangle {
width: u32,
height: u32,
}
impl Rectangle {
// This is an instance method.
fn area(&self) -> u32 {
self.width * self.height
}
// This is another instance method.
fn can_hold(&self, other: &Rectangle) -> bool {
self.width > other.width && self.height > other.height
}
// This is an associated function.
fn square(size: u32) -> Rectangle {
Rectangle {
width: size,
height: size,
}
}
}
fn main() {
let rect1 = Rectangle {
width: 30,
height: 50,
};
let rect2 = Rectangle {
width: 10,
height: 40,
};
let rect3 = Rectangle {
width: 60,
height: 45,
};
println!("The area of the rectangle is {} square pixels.", rect1.area());
println!("Can rect1 hold rect2? {}", rect1.can_hold(&rect2));
println!("Can rect1 hold rect3? {}", rect1.can_hold(&rect3));
let square = Rectangle::square(20);
println!("Square rectangle: {} x {}", square.width, square.height);
}
In the signature for area
, we use &self
instead of rectangle: &Rectangle
. The &self
is actually short for self: &Self
. Within an impl
block, the typeSelf
is an alias for the type that the impl
block is for. Methods must have a parameter named self
of type Self
for their first parameter, so Rust lets you abbreviate this with only the name self
in the first parameter spot. Note that we still need to use the &
in front of the self
shorthand to indicate that this method borrows the Self
instance, just as in rectangle: &Rectangle
. Methods can take ownership of self
, borrow self
immutably, as we’ve done here, or borrow self
mutably, just as they can any other parameter.
self
, &self
, and &mut self
- self: Consumes the instance. The method takes ownership of the instance, which means the instance will be moved.
- &self: Borrows the instance immutably. This allows the method to read from the instance without taking ownership.
- &mut self: Borrows the instance mutably. This allows the method to modify the instance.
Top comments (0)