Mutably borrowing self

Sometimes, a function needs to change its self. For those situations, we can receive self as a mutable borrow with &mut self. Like any other time we create a mutable borrow, we can only call such a function if we have the value for self stored in a mutable variable, and that value is not currently borrowed anywhere else. In other words, we can only call functions that have write access to a value when we ourselves have write access to that value.

Here, we have an example function that mutable borrows self:

impl Point2D {
// ...
pub fn unit(&mut self) {
let mag = self.magnitude();
self.x = self.x / mag;
self.y = self.y / mag;
}
}

We see several things here. First, we are able to call the read-only magnitude function on self, even though that function takes its self as an immutable borrow, and we've got our self value as a mutable borrow. The reverse is not true: if we tried to call the unit function from inside of the magnitude function, the compiler would refuse to allow it.

Second, since we have write access to self, we can change the data stored in it. That's what write access means.

Third, we don't have a return type specified for this function. Technically, it defaults to returning (), but that's just another way of saying it doesn't return anything meaningful. It's common practice for functions that change self to not return a value or to return a Result with () as its success value if the function needs the ability to report errors. That's because the real result of the function is the updated self value.

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

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