The instance methods are applied onto an existing object. Inside the
header and the body of the method, this instance is represented by the
self keyword. As with other arguments, we can apply the keyword mut
and/or the reference operator & onto self.
In the following example, the self instance is moved into the method,
and made mutable so we can modify a field. The instance is then returned
at the end of the method. Note the return type declaration with the
Self keyword that represents the type of the self instance:
fn with_size(mut self, size: usize) -> Self {
self.size = size;
self
}In this other example, the size() method takes the self instance as
a reference, thus it will not be moved. We then return the value of a
field:
fn size(&self) -> usize {
self.size
}