My understanding so far was that in Rust, operators are basically syntactic sugar for trait method calls. In particular, I thought that a += b
was equivalent to writing a.add_assign(b)
. I was very suprised today to hear the following from rustc (1.44.1):
error[E0368]: binary assignment operation `+=` cannot be applied to type `&mut u8`
--> src/main.rs:2:5
|
2 | a += b;
| -^^^^^
| |
| cannot use `+=` on type `&mut u8`
|
help: `+=` can be used on 'u8', you can dereference `a`
|
2 | *a += b;
| ^^
The code responsible for the error message is (Playground)
fn test_add_assign(a: &mut u8, b: u8) {
a += b;
}
fn main() {
let mut test = 1;
test_add_assign(&mut test, 1);
assert_eq!(test, 2);
}
Now, the compiler is correct, writing *a += b
works and also correctly assigns the new variable to a. To my suprise, however, also a.add_assign(b)
works perfectly fine without the need to dereference a
(Playground):
fn test_add_assign(a: &mut u8, b: u8) {
a.add_assign(b);
}
Given that the documentation for AddAssign
simply states
The addition assignment operator
+=
.
I am wondering: What is the relationship between AddAssign
and the +=
operator, if it is not basically syntactic sugar for calling the trait method?