我在处理结构体的生命周期参数时遇到了问题。我不确定如何准确地描述这个问题,但是我创建了一个简单的示例来展示我的编译时错误。
struct Ref;
struct Container<'a> {
r : &'a Ref
}
struct ContainerB<'a> {
c : Container<'a>
}
trait ToC {
fn to_c<'a>(&self, r : &'a Ref) -> Container<'a>;
}
impl<'a> ToC for ContainerB<'a> {
fn to_c(&self, r : &'a Ref) -> Container<'a> {
self.c
}
}
我遇到的错误是
test.rs:16:3: 18:4 error: method `to_c` has an incompatible type for trait: expected concrete lifetime, but found bound lifetime parameter 'a
test.rs:16 fn to_c(&self, r : &'a Ref) -> Container<'a> {
test.rs:17 self.c
test.rs:18 }
test.rs:16:48: 18:4 note: expected concrete lifetime is the lifetime 'a as defined on the block at 16:47
test.rs:16 fn to_c(&self, r : &'a Ref) -> Container<'a> {
test.rs:17 self.c
test.rs:18 }
error: aborting due to previous error
我尝试了许多变化,但就是无法编译它。我在这里找到了另一篇文章(如何解决:预期具体生命周期,但发现了绑定的生命周期参数),但它似乎是绕过问题而不是解决问题。我实在看不出问题甚至是从哪里开始的。&Ref通过移动被传递,所以它应该可以正常工作,对吧?
有什么想法吗?感谢所有的帮助。
trait ToC<'a> { fn to_c(&self, r: &'a Ref) -> Container<'a>; }
。 - huonimpl<'a> ToC<'a> for ContainerB<'a>
。 - Chris Morgan