我有一個結構A
與盒裝性狀(Foo
),另一個結構BoxedA
它有一個Rc<RefCell<A>>
。我試圖在BoxedA
上創建一個方法,該方法返回參考盒裝特性,但在將Ref<A>
映射到Ref<Foo>
時仍然遇到有關生命期的問題。當使用Ref :: map與特徵對象時,無法推斷出生命週期
這裏是我的代碼:
use std::rc::Rc;
use std::cell::{RefCell, Ref};
trait Foo {
}
struct A {
a: Box<Foo>
}
impl A {
fn new(a: Box<Foo>) -> A {
A { a: a }
}
fn a(&self) -> &Foo {
&*self.a
}
}
struct BoxedA {
a: Rc<RefCell<A>>
}
impl BoxedA {
fn new(a: Box<Foo>) -> BoxedA {
BoxedA {
a: Rc::new(RefCell::new(A::new(a)))
}
}
fn a(&self) -> Ref<Foo> {
Ref::map(self.a.borrow(), |a| a.a())
}
}
impl Foo for i32 {
}
fn main() {
let a = BoxedA::new(Box::new(3));
let a_ref = a.a();
}
鏽操場鏈接:https://play.rust-lang.org/?gist=d0348ad9b06a152770f3877864b01531&version=stable&backtrace=0
我獲得以下編譯錯誤:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> <anon>:34:41
|
34 | Ref::map(self.a.borrow(), |a| a.a())
| ^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the body at 34:38...
--> <anon>:34:39
|
34 | Ref::map(self.a.borrow(), |a| a.a())
| ^^^^^
note: ...so that reference does not outlive borrowed content
--> <anon>:34:39
|
34 | Ref::map(self.a.borrow(), |a| a.a())
| ^
note: but, the lifetime must be valid for the anonymous lifetime #1 defined on the body at 33:28...
--> <anon>:33:29
|
33 | fn a(&self) -> Ref<Foo> {
| _____________________________^ starting here...
34 | | Ref::map(self.a.borrow(), |a| a.a())
35 | | }
| |_____^ ...ending here
note: ...so that the declared lifetime parameter bounds are satisfied
--> <anon>:34:9
|
34 | Ref::map(self.a.borrow(), |a| a.a())
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
奇怪的是,代碼編譯,如果我全部更換Foo
的用i32
。