Closed
Description
I'm quite experienced with pointers and references (in languages like C, C++, Java, Go, etc.) but this example in the Pointers chapter confused me:
fn main() {
let x = &mut 5;
if *x < 10 {
let y = &x;
println!("Oh no: {}", y);
return;
}
*x -= 1;
println!("Oh no: {}", x);
}
I was confused by &mut 5
(taking the address of a numeric literal is a syntax error in languages I'm used to, and being able to mutate the literal is even weirder!), and also by the fact that y
ends up being a pointer to a pointer.
It got clearer when I figured out that neither of those things is relevant. In fact the type of x
is a red herring — it doesn't matter in the example (and the following one) what the type of x
is, just that we both create a reference to it and modify it.
I think changing x
to an integer would clarify the example:
fn main() {
let mut x = 5;
if x < 10 {
let y = &x;
println!("Oh no: {}", y);
return;
}
x -= 1;
println!("Oh no: {}", x);
}
Metadata
Metadata
Assignees
Labels
No labels