[英]How can i specify struct lifetime in rust implementation for trait with static lifetime?
I have this code:我有这段代码:
// 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);
}
I need the dispatcher field in the structure, but when specifying the field type, I also need to specify the lifetime.我需要结构体中的dispatcher字段,但是在指定字段类型的时候,还需要指定lifetime。 This is not a problem as long as I don't have to specify a lifetime in the GameState
implementation block which has a static lifetime.只要我不必在具有 static 生命周期的GameState
实现块中指定生命周期,这就不是问题。 When I try to specify the lifetime there, I get an error.当我尝试在那里指定生命周期时,出现错误。 I can't change the GameState
and Dispatcher
because it's library code and I need the dispatcher field in the struct.我无法更改GameState
和Dispatcher
,因为它是库代码,我需要结构中的调度程序字段。 How can I solve this problem?我怎么解决这个问题?
Full error text:完整的错误文本:
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
You have to define all lifetimes that Engine
contains as 'static
because by writing trait Gamestate: 'static
you say that Gamestate
can only be implemented for things that contain no references that live shorter than 'static
but by trying to define it for a struct containing references of a generic lifetime 'a
which you have to assume can be any lifetime in practice this obviously isn't fulfilled.您必须将Engine
包含的所有生命周期定义为'static
因为通过编写trait Gamestate: 'static
你说Gamestate
只能针对不包含比'static
寿命短的引用的事物来实现,但是通过尝试为包含的结构定义它你必须假设的通用生命周期'a
引用在实践中可以是任何生命周期,这显然没有实现。
Wether you do it by directly secifying it in Engine
, Dispatcher
or by passing 'static
as generic parameters is up to you to decide, do you need to support non-static lifetimes in a Engine
?无论您是通过直接在Engine
、 Dispatcher
中对其进行分类还是通过将'static
作为通用参数传递都由您决定,您是否需要在Engine
中支持非静态生命周期? Then you definitely can't use 'static
in it's definition, similar for Dispatcher
.那么你绝对不能在它的定义中使用'static
,类似于Dispatcher
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.