Moving self

If the self value is moved into the function, it's just like moving any other value; we can't continue to use it where it used to be anymore. Here is a function:

impl Point2D {
pub fn transpose(self) -> Point2D {
return Point2D {x: self.y, y: self.x};
}
}

This can be said to consume the self value. The value is moved into the function's scope when it is called, and the old variable that used to contain the value is no longer usable. This particular function returns a new, different Point2D value, so the value of self is completely gone once this function is done running.

There are reasons why this might be exactly the behavior we want. In the previous example, the function transforms the self value into something new, which is reflected by having it consume the old value.

A very common use of functions that consume self is the builder pattern. This is a design pattern in Rust where we construct complex data structures bit by bit by filling in values to a builder structure, and then call a build function implemented on the builder structure to construct our final data value. Most of the time, the build function will consume its self, since each builder value should be used to construct only one final value.

The builder pattern is essentially a way to use Rust's syntax to achieve the same things that are achieved by keyword arguments and default values in some other languages.

Any time the value of self will be invalidated by what the function does, either literally or conceptually, it makes sense to move self into the function's scope.

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

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