When to use * when editing variable

fn main() {
    let mut a:Vec<i64> = Vec::new();


    println!("{:?}", a.to_owned());

    let b = &mut a;

    (*b).push(1); // works b.push(1); also (without *)

    println!("{:?}", b);
    println!("{:?}", a);

    let mut c = 1;
    let d = &mut c;

    *d += 1; // why is * needed in this case?



In the code, when using vector, .push() works with * or without *.

But when using integer, * is necessary.

How could I determine to use or not * when modifying an object?

This has nothing to do with whether the type is Vec or an integer. It's simply that method calls auto-reference (and auto-dereference) as much as needed; Vec::push() takes &mut self, so if you have a mutable binding, the compiler will automatically take the address when you call push().

Because you are adding to the integer, not to the reference.


Auto-dereferencing works with method calls (see method-call expressions), but not, for example, with assignments.


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.