gpt4 book ai didi

rust - 谁借用了一个变量?

转载 作者:行者123 更新时间:2023-11-29 07:42:37 25 4
gpt4 key购买 nike

我在和借阅检查员打架。我有两段相似的代码,一段按我的预期工作,另一段不正常。

如我所料的:

mod case1 {
struct Foo {}

struct Bar1 {
x: Foo,
}

impl Bar1 {
fn f<'a>(&'a mut self) -> &'a Foo {
&self.x
}
}

// only for example
fn f1() {
let mut bar = Bar1 { x: Foo {} };
let y = bar.f(); // (1) 'bar' is borrowed by 'y'
let z = bar.f(); // error (as expected) : cannot borrow `bar` as mutable more
// than once at a time [E0499]
}

fn f2() {
let mut bar = Bar1 { x: Foo {} };
bar.f(); // (2) 'bar' is not borrowed after the call
let z = bar.f(); // ok (as expected)
}
}

没有的:

mod case2 {
struct Foo {}

struct Bar2<'b> {
x: &'b Foo,
}

impl<'b> Bar2<'b> {
fn f(&'b mut self) -> &'b Foo {
self.x
}
}

fn f4() {
let foo = Foo {};
let mut bar2 = Bar2 { x: &foo };
bar2.f(); // (3) 'bar2' is borrowed as mutable, but who borrowed it?
let z = bar2.f(); // error: cannot borrow `bar2` as mutable more than once at a time [E0499]
}
}

我希望我可以调用 Bar2::f 两次而不会激怒编译器,就像情况 1 一样。

问题在评论(3)中:谁借用了bar2,而没有做作?

这是我的理解:

  1. 在情况 1 中,f2 调用:生命周期参数 'a 是接收的 &Foo 值之一,所以这没有做作时lifetime为空,Bar1::f调用后bar不被借用;

  2. 在情况2中,bar2借用了foo(作为不可变的),所以Bar2中的生命周期参数'b 结构是 foo 引用生命周期,它在 f4 体的末尾结束。调用 Bar2::f 在该生命周期内借用 bar2,即到 f4 的末尾。

但问题依旧:bar2是谁借的?可以是 Bar2::f 吗? Bar2::f 在调用后如何持有借用的所有权?我在这里缺少什么?

我在 x86_64-pc-windows-msvc 上使用 Rust 1.14.0-nightly (86affcdf6 2016-09-28)。

最佳答案

啊……你基本上是自己借的。

问题取决于这样一个事实,即您有相同的生命周期 ( 'b ) 用于 Foo 的生命周期。和 Bar 的生命周期.然后,编译器尽职尽责地统一了这些生命周期,你最终会遇到一种奇怪的情况,即本应在语句末尾结束的借用生命周期突然在值应该超出范围之后结束。

根据经验:始终self 使用新的生命周期.其他任何事情都很奇怪。


有趣的是,这个模式实际上很有用(尽管更可能是不可变借用):它允许锚定一个值到栈帧,防止调用函数后的任何移动,这(有时)可用于表示 Rust 未很好建模的借用(例如将指向值的指针传递给 FFI)。

关于rust - 谁借用了一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39827244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com