![](/img/trans.png)
[英]How to implement a trait with 'static lifetime for a struct with lifetime 'a?
[英]How can i specify struct lifetime in rust implementation for trait with static lifetime?
我有这段代码:
// engine.rs
pub struct Engine<'a, 'b> {
// ...some code
dispatcher: Dispatcher<'a, 'b>
}
impl<'a, 'b> GameState for Engine<'a, 'b> { // <- Error
fn tick(&mut self, ctx: &mut BTerm) {
todo!()
}
}
// dispatcher.rs (lib file)
pub struct Dispatcher<'a, 'b> {
//...some code
}
// gamestate.rs (lib file)
pub trait GameState: 'static {
fn tick(&mut self, ctx: &mut BTerm);
}
我需要结构体中的dispatcher字段,但是在指定字段类型的时候,还需要指定lifetime。 只要我不必在具有 static 生命周期的GameState
实现块中指定生命周期,这就不是问题。 当我尝试在那里指定生命周期时,出现错误。 我无法更改GameState
和Dispatcher
,因为它是库代码,我需要结构中的调度程序字段。 我怎么解决这个问题?
完整的错误文本:
error[E0478]: lifetime bound not satisfied
--> src/engine.rs:14:14
|
14 | impl<'a, 'b> GameState for Engine<'a, 'b> {
| ^^^^^^^^^
|
note: lifetime parameter instantiated with the lifetime `'b` as defined here
--> src/engine.rs:14:10
|
14 | impl<'a, 'b> GameState for Engine<'a, 'b> {
| ^^
= note: but lifetime parameter must outlive the static lifetime
您必须将Engine
包含的所有生命周期定义为'static
因为通过编写trait Gamestate: 'static
你说Gamestate
只能针对不包含比'static
寿命短的引用的事物来实现,但是通过尝试为包含的结构定义它你必须假设的通用生命周期'a
引用在实践中可以是任何生命周期,这显然没有实现。
无论您是通过直接在Engine
、 Dispatcher
中对其进行分类还是通过将'static
作为通用参数传递都由您决定,您是否需要在Engine
中支持非静态生命周期? 那么你绝对不能在它的定义中使用'static
,类似于Dispatcher
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.