&A; } #[derive(Debug)] struct A { v: i32, } impl A { fn nb-6ren">
gpt4 book ai didi

rust - 由于需求冲突,将结构转换为具有生命周期的特征得到 "cannot infer an appropriate lifetime for lifetime parameter ` 'a`”

转载 作者:行者123 更新时间:2023-11-29 08:13:58 27 4
gpt4 key购买 nike

trait BT {
fn get_a(&self) -> &A;
}

#[derive(Debug)]
struct A {
v: i32,
}

impl A {
fn nb(&self) -> Box<BT> {
Box::new(B { a: self })
}
}

#[derive(Debug)]
struct B<'a> {
a: &'a A,
}

impl<'a> BT for B<'a> {
fn get_a(&self) -> &A {
return self.a;
}
}

fn main() {
println!("{:?}", A { v: 32 }.nb().get_a());
}

A 有一个生成 B 实例的方法,它引用了 A,而 B 可能有许多方法访问 B.a(A 在 B 中的引用)。如果让 A.nb() 返回 B 而不是 BT,代码将运行良好。

我是 Rust 新手。这个问题困扰了我一整天。我应该怎么做才能使这段代码工作?谢谢!

整个错误报告:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter `'a` due to conflicting requirements
--> src\socket\msg\message.rs:53:26
|
53 | Box::new(B{a: self})
| ^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 52:13...
--> src\socket\msg\message.rs:52:13
|
52 | / fn nb(&self) -> Box<BT> {
53 | | Box::new(B{a: self})
54 | | }
| |_____________^
note: ...so that reference does not outlive borrowed content
--> src\socket\msg\message.rs:53:31
|
53 | Box::new(B{a: self})
| ^^^^
= note: but, the lifetime must be valid for the static lifetime...
= note: ...so that the expression is assignable:
expected std::boxed::Box<socket::msg::message::test::test::BT + 'static>
found std::boxed::Box<socket::msg::message::test::test::BT>

最佳答案

特征对象的默认生命周期是'static。您需要为 nb() 函数返回的特征对象添加一个明确的生命周期绑定(bind):

impl A {
fn nb<'s>(&'s self) -> Box<BT+'s> {
Box::new(B{a: self})
}
}

Inference of Trait Object Lifetimes

关于rust - 由于需求冲突,将结构转换为具有生命周期的特征得到 "cannot infer an appropriate lifetime for lifetime parameter ` 'a`”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50248219/

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