When can I omit dereferencing using the asterisk operator?

I find it difficult to understand when to use the asterisk operator to dereference and when I can 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 example is almost compiled, with the exception of the last statement, where I add it to a mutable link x. There I get this error:

the trait bound `_: std::ops::Add<&mut _>` is not satisfied [E0277]

In any case, stars and non-steric versions are valid, and give the expected results.

+4
source share
1 answer

, , Add. , 1 + *x, *x i32 i32 + i32. i32 + &i32 ( &i32 + i32 &i32 + &i32), b, , , , &&i32 &mut i32. d .

+4

All Articles