Rust borrowing when adding to a reference?

huangapple go评论56阅读模式
英文:

Rust borrowing when adding to a reference?

问题

我不理解这个,

为什么编译器在 let co = 0; co += &1; 上报错,不能将 co 借用为可变的,

但在 let co = 0; co += 1; 上报错,不能两次赋值给不可变变量 co

为什么 co 被借用?

我期望 co 不被借用。

英文:

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

答案1

得分: 1

两个示例显示了不同的错误消息,但在本质上并不有意思,因为它们都基于同样的基本原则出错:co 没有被标记为可变,所以你不能用 += 进行改变。

后一个错误消息看起来更为特定,因此希望通过直接解决赋值的问题来更有帮助。前一个错误消息似乎更通用,即“无法借用 _ 为可变”,适用范围更广。

为什么 co 被借用?我期望 co 不会被借用。

+= 的实现是通过 AddAssign trait 完成的,它需要接受左侧作为可变引用以便进行修改。这就是为什么借用会发生,但错误当然指出了不可创建可变借用,因为 co 不是可变的。

英文:

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.

huangapple
  • 本文由 发表于 2023年2月6日 11:49:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75357184.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定