Rizal Fathoni Aji
Rizal Fathoni Aji

Reputation: 11

Rust borrowing when adding to a reference?

I don't understand this one,

why is the compiler error on let co = 0; co += &1; cannot borrow co as mutable

but errors on let co = 0; co += 1; cannot assign twice to immutable variable co?

why is co borrowed ?

I expect co to not be borrowed

Upvotes: 0

Views: 133

Answers (1)

kmdreko
kmdreko

Reputation: 59827

Interesting that the two examples show such different error messages, but not meaningfully interesting since they both error-out on the same basic principle: co is not marked as mutable, so you can't mutate it with +=.

The latter error message looks more specialized and therefore hopes to be more helpful by directly addressing the problem of assignment. The former error message appears to be the more general "cannot borrow _ as mutable" which applies more widely.

Why is co borrowed? I expect co to not be borrowed.

The implementation of += is done through the AddAssign trait which needs to accept the left-hand side as a mutable reference in order to mutate it. That is why the borrow happens, but the error of course indicates that a mutable borrow cannot be created since co is not mutable.

Upvotes: 1

Related Questions