Completely new to rust here, so bear with me.
Just started with the rustbook, beeing on chapter 2 for creating the guessing game. While I dont have problemes writing that stuff, I struggle reading the docs.
Specificially talking about following line of code: let secret_number = rand::thread_rng().gen_range(1..=100);
I was curious about get_range() and had a look at the docs where it's written something like this: fn gen_range)<T, R>(&mut self, range: R) -> T
For me, this should take two parameters. While I don't understand the reason for &mut self, why only providing one parameter is enough?
I'm not completely new to programming, but I just cant make a sense of this.
You are looking at a method and not a free function. Methods are implemented for a type (the Self type) and take some sort of self as an argument, i.e. &self, &mut self, self, self: Box<Self>, etc., which gives you access to the concrete instance of the type the method can be called on. Just like methods of classes work in OOP languages. Especially Python is relatable, because it also takes the object as the first argument of a method (also by convention called self, though in Rust self is a mandatory keyword for a method), where other languages omit this argument and allow access to the object through keywords, like this in Java and such. Methods are explained a little later in the book:
Just to be pendantic....
If you want to call a "method" as a "free function" you can. The syntax using '.' is sugar.
fn main() {
let mut rand_generator = rand::thread_rng();
let secret_number = rand::Rng::gen_range(&mut rand_generator, 1..=100);
println!("The secret number is: {secret_number}");
}
Even though this clears up things a bit more, hopefully you're not mad at me letting jofa's answer still be the solution to my problem, since he gave me hints of where it all comes from and where to get further reading.