Dhghomon / easy_rust

Rust explained using easy English
MIT License
8.1k stars 380 forks source link

Regular methods do not take self, only &self #118

Closed hoijui closed 3 years ago

hoijui commented 3 years ago

When reading this sentence, I was wondering if all three could be used - self, &self and &mut self - or just the later two. I wanted to make more clear that only the later two. ... That is the case, right?

Dhghomon commented 3 years ago

They can actually take all three, including self - here's an example:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9ea6de6c7664da35a003e00904bc4bf5

You might be wondering what the use of that is, and here's one example:

https://dhghomon.github.io/easy_rust/Chapter_55.html

With this pattern you pull in self and declare it as mutable (you're taking ownership so you can just declare it as mutable - it's not a mutable reference) and then make a change and pass it back out. That's the pattern that lets you chain methods like this to make it easy for others to build their own types:

let my_character = Character
.strength(10)
.dexterity(15)
.charisma(18)
.build();
hoijui commented 3 years ago

wow cool! thanks a lot! That makes sense to have!

do you think this info should be in your book at this point, or would it not fit there/be too advanced at this point? I guess, as you did not add it... you want it so.. good! :-)

... maybe make the self (without reference) a link to this issue?