Why dereferencing `&mut self` is not required?

#[derive(Debug, PartialEq)]
struct Integer(i32);

impl Integer {
    fn add(&mut self, num: i32) {
        // (*self).0 += num; // why `*` is not required
        self.0 += num;
    }
}

#[test]
fn mutable_reference_self() {
    let mut i = Integer(7);
    i.add(3);                // implicit call
    Integer::add(&mut i, 2); // explicit call
    assert_eq!(i, Integer(12));
}

In this example, the parameter self is a mutable reference (self: &mut Self) of custom type Integer. In theory, to mutate the value that self is pointing to, dereferencing is required (*self). Is that Rust simply allows us to omit the * operator for the sake of convenience? Or, am I missing something?

I might be asking a basic and obvious question. But I can't find any similar question online, and Rust Book never mentions this. I'm not confident enough to assert myself.

Field access automatically dereferences if needed.

1 Like

Ahh, I didn't know that we can access struct field directly without dereferencing :man_facepalming:. Thanks.

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.