Borrowing self

If the self value is immutably borrowed into a function, then that function has read-only access to the value. This is useful in many situations, because it lets us call the function without making a copy of the self value for it to operate on, and without making the compiler ensure that the rules of write access are maintained.

Here's an example of a function that immutably borrows self:

impl Point2D {
// ...
pub fn magnitude(&self) -> f64 {
return (self.x.powi(2) + self.y.powi(2)).sqrt();
}
}
This function returns , or in other words, the distance between the point stored in self and the origin of the coordinate system.

The magnitude function doesn't need to change self, so there's no reason for it to use a mutable borrow and deal with the restrictions that implies. It could have worked with a moved self, but there's nothing wrong with calling the magnitude function twice on the same value, so that isn't what we want either.

Using an immutable borrow for self is most often the correct choice. We need a reason to use self or &mut self, and if we don't have such a reason, we use &self.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.141.27