I have a hard time understanding when to use the asterisk operator for dereferencing and when can I omit it.
fn main() { a(); b(); c(); d(); }
fn a() {
let v = 1;
let x = &v;
println!("a {}", *x);
println!("a {}", 1 + *x);
}
fn b() {
let v = 1;
let x = &v;
println!("b {}", x);
println!("b {}", 1 + x);
}
fn c() {
let mut v = 1;
let mut x = &mut v;
println!("c {}", *x);
println!("c {}", 1 + *x);
}
fn d() {
let mut v = 1;
let mut x = &mut v;
println!("d {}", x);
println!("d {}", 1 + x); // error
}
The above code sample almost compiles except the last statement where I add one to the the mutable reference x
. There I get this error:
the trait bound `_: std::ops::Add<&mut _>` is not satisfied [E0277]
Anywhere else both asterisk and non-asterisk versions are valid and give expected results.