Hello
In the mentioned chapter, rust book 8.5.1.4, the comment claims implicitly that the *
is needed to avoid the &
before val.
// To avoid the `&`, you dereference before matching.
match *reference {
val => println!("Got a value via dereferencing: {:?}", val),
}
Output:
Got a value via dereferencing: 4
I find that I get the same output with (no *
in front of "reference" and no &
in front of "val"):
match reference {
val => println!("Got a value via dereferencing: {:?}", val),
}
Tried replacing {:?}
with {}
to ensure I am not cheated by debug interpretation somehow, but that produced the same "correct" output.
My compiler version:
$ rustc --version
rustc 1.66.0 (69f9c33d7 2022-12-12) (Arch Linux rust 1:1.66.0-1)
I am confused by what // To avoid the `&`, you de-reference before matching.
tries to tell me and therefore what is going on in the code. My assumption is that the missing *
in front of "reference" and there not being an &
in front of "val" would print the address at which the integer 4
is stored, not the integer itself? I would be shocked to find that the address this integer is stored at is by chance 4
, so i changed the number to 3. Here is the complete code with all modificaitons, producing 2 lines of identical output:
fn main() {
let reference = &3;
match reference {
&val => println!("Got a value via destructuring: {:?}", val),
}
match reference {
val => println!("Got a value via dereferencing: {}", val),
}
}
Rust playground behaves the same.