fn main()
{
let mut x = 10;
let a = &mut x;
a += 20; // Not allowed
println!("{}", a);
}
Why am I not allowed to add values to a
variable
fn main()
{
let mut x = 10;
let a = &mut x;
a += 20; // Not allowed
println!("{}", a);
}
Why am I not allowed to add values to a
variable
As the compiler says:
cannot use `+=` on type `&mut {integer}`
help: `+=` can be used on '{integer}', you can dereference `a`
*a += 20;
It's because impl AddAssign<i32> for &mut i32
doesn't exist.
And the reason for that is explicitness, more information in this topic.
Then how come for strings I don't have to use a dereference if I wanted to push_str()
some random data?
That is due to reference coercion, where if you try to say x.foo()
, then no matter if x: T
or x: &T
, it will call it. On the other hand this is because of explicitness where we want to explicitly say, the memory location under x
must have 20 added to it.
Oh ok thanks, that makes sense.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.