构建FooBuilder
时,我想提供一个&mut Bar
。当我建立Foo
我想提供一个&Bar
和Foo
应该能够从Bar
调用&self
方法。换句话说,可变借款只能在FooBuilder
的生命期间存在。如何给构建器一个可变引用,但只有对构建对象的不可变引用?
struct FooBuilder<'a> {
bar: &'a mut Bar,
}
impl<'a> FooBuilder<'a> {
fn new(bar: &'a mut Bar) -> Self {
FooBuilder { bar: bar }
}
fn build(&'a self) -> Foo<'a> {
Foo { bar: &self.bar }
}
}
struct Foo<'a> {
bar: &'a Bar,
}
struct Bar;
impl Bar {
fn bar(&self) {}
}
fn main() {
let mut bar = Bar;
let foo = FooBuilder::new(&mut bar).build();
bar.bar();
}
这段代码有错误:
error: borrowed value does not live long enough
--> <anon>:24:15
|
24 | let foo = FooBuilder::new(&mut bar).build();
| ^^^^^^^^^^^^^^^^^^^^^^^^^ does not live long enough
|
note: reference must be valid for the block suffix following statement 1 at 24:48...
--> <anon>:24:49
|
24 | let foo = FooBuilder::new(&mut bar).build();
| ^
note: ...but borrowed value is only valid for the statement at 24:4
--> <anon>:24:5
|
24 | let foo = FooBuilder::new(&mut bar).build();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: consider using a `let` binding to increase its lifetime
--> <anon>:24:5
|
24 | let foo = FooBuilder::new(&mut bar).build();
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
error[E0502]: cannot borrow `bar` as immutable because it is also borrowed as mutable
--> <anon>:25:5
|
24 | let foo = FooBuilder::new(&mut bar).build();
| --- mutable borrow occurs here
25 | bar.bar();
| ^^^ immutable borrow occurs here
26 | }
| - mutable borrow ends here
error: aborting due to 2 previous errors
你的问题到底是什么? – antoyo
这不是修改问题的最佳礼仪,它会使现有答案失效。 – Shepmaster
我不认为这是可能的,对不起。您无法将可变引用降级为共享引用,以重新获得共享生存期。 – Veedrac