为什么参数“借用"价值? [英] Why does the parameter "borrow" the value?
问题描述
这是一个示例:
struct X(u32);
impl X {
fn f(&mut self, v: u32) {}
}
fn main() {
let mut x = X(42);
// works
let v = x.0;
x.f(v);
// cannot use `x.0` because it was mutably borrowed
x.f(x.0);
}
(Rust 游乐场)
error[E0503]: cannot use `x.0` because it was mutably borrowed
--> src/main.rs:16:9
|
16 | x.f(x.0);
| - ^^^ use of borrowed `x`
| |
| borrow of `x` occurs here
x.f(x.0)
不起作用的原因是什么?x.0
作为参数传递,绑定到 v
参数,类型为 u32
:绝对不可能访问函数体x.0
通过参数.
What is the reason why x.f(x.0)
does not work? x.0
is passed as an argument, bound to the v
parameter, of type u32
: there is absolutely no possibility that the function body access x.0
through the parameter.
此外,我觉得这很奇怪:
Moreover, it seems very weird to me that:
f(something);
不起作用,同时:
v = something;
f(v);
有效.
推荐答案
当你做xf(x.0)
时,你借用了x
来提供x
以获取对 x.0
的引用之前,>&mut self 到 f
.不可能同时引用 x.0
两次.也就是说,方法 f
不能同时通过 &mut self
(包括 x.0
) 和对 x.0
的看似不可变的引用.
When you do x.f(x.0)
, you have borrowed x
to provide the &mut self
to f
before trying to borrow x
again to get a reference to x.0
. It is not possible to refer to x.0
twice at the same time. That is, the method f
can't have both mutable access to x
via &mut self
(which includes x.0
) and a seemingly immutable reference to x.0
at the same time.
当使用临时变量时,你实际上得到了一个值的副本;这意味着你不再引用X中的int
而是42
.这是允许的.
When using a temporary variable, you actually get a copy of the value; this means you no longer refer to that int in X
but 42
. That's allowed.
关于非词法生命周期"评论:由于 f
使用一个很好的旧 u32 而不是对它的引用,xf(x.0)
基本上应该是等价于xf(42)
,因为编译器在从x.0
中取出值后可以放开x
然后mut-borrowx
再次提供 &mut self
给 f
.但是,编译器在编译期间很早就确定了生存期及其要求;因此,目前的寿命比它们必须的要宽.由于 x.0
参数,rustc
当前无法确定 x
上的借用在借用 x
之前已经结束> 用于 &mut self
.正在工作解决这个问题.
Regarding the "non-lexical lifetimes" comments: Since f
takes a good old u32 instead of a reference to it, x.f(x.0)
should basically be equivalent to x.f(42)
, because the compiler can let go of x
after getting the value out of x.0
and then mut-borrow x
again to provide &mut self
to f
. However, the compiler determines the lifetimes and their requirements very early on during compilation; lifetimes are therefor currently broader than they have to be. rustc
is currently unable to determine that the borrow on x
due to the x.0
argument has ended before borrowing x
for &mut self
. There is work underway to fix this.
这篇关于为什么参数“借用"价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!