Methods are similar to functions.
They differ because methods are defined within the context of a struct, enum or trade object.
Methods always have their first parameter as self, which is representing the instance of the drug that
is calling the method.
So let's create a struct real quick called square.
And we're going to have the width and height.
Then let's create
a square.
We're going to say the width is five and the height is five.
All right.
So awesome.
So we got our square created.
So in order to.
Create these methods.
We start off with the simple keyword which stands for Implement and then the name of the structure that
we want to implement these on.
So we want to implement some methods on a square and then just like what's normal with a function,
we say function so f an area and then remember the first parameter is always self.
And then in this case we want to return an unsigned 32 and since we're doing the area we're going to
do with.
Times high.
So if we come down here and print this out, we would expect to see 25.
And that's exactly what we got.
So we can have as many of these functions as we want.
So is another one.
Let's just call What's my width if I can spell it right.
And we're going to refer to self.
We're going to return an unsigned 32 and we're just going to return self with and again, just to see
how this works, let's print it out.
Field, not a method.
And that's because it's called What's My Width?
That would help.
And we got five back.
So that's how you create methods with.
Trucks.
But now what if we want to have a mutable stroke?
How can we go about that?
Well in here we would need to make square mutable.
So now that we did that, so let's create a function called change width and we're going to obviously
exempt ourself.
And then I also want to say, hey, new width of type use 32 and then we're going to say self dot width
equals new width.
So down here we would say square dot change with in my new width we're going to make it ten, which
even though now makes it a rectangle.
But for the sake of this, we'll say it is still a square.
So now if we print it out again, we would expect it to print out ten now, which it does not.
So let's see what my error is.
So it says self is a reference.
So the data it refers to cannot be written.
So we need it to be.
And.
Mutable and now that it works.
So we updated our width through a mutable reference to the square struck.
So it works the same way as we learned in the last section with mutable references.
But in this case we had to make our self mutable and the function call, and then we also had to make
our variable mutable.
So in the next lecture, we're going to look over what life times are, as well as the history and why
lifetimes are.
Even in rust and what exactly they do for us.