Struct Methods
First up - methods within in Structs can manipulate and work with data within a Struct.
When we call a function inside a struct, the first parameter to the function is always a reference to the struct itself.
That explains why you might have seen the keyword self thrown around in Rust code. This is so the struct method has access to the data within the struct instance.
The methods are defined using something called Implementation blocks. They 'implement' on types:
impl my_struct {
}
Then, inside what is called an impl block (which uses the same name as the original struct), we create a function block as normal, but set the first parameter as a reference to self, not forgetting to set a return type on the function (in this case a str reference), but it can be a u8, f32 etc:
impl my_struct {
fn get_name(&self) -> &str {
&self.name
}
}
You can see here, that the function returns the struct reference, but also the variable inside the struct, accessed using dot notation.
Okay. So what if we want to write a function that sets values in a struct? Well, if we do that, we need to create an impl which takes a mutable &self, since we need to change the struct values which we are referencing. No return value, since we are updating an existing struct.
impl my_struct {
fn set_name(&mut self, name: String) {
self.name = name;
return
}
}