![](/img/trans.png)
[英]Tokio / Tonic - How to fix this error: `self` has lifetime `'life0` but it needs to satisfy a `'static` lifetime requirement
[英]Cannot satisfy `'static` lifetime requirement
我正在嘗試使用yew
創建一個應用程序。 我有一個玩家列表,我想將他們的狀態從活動狀態切換為非活動狀態,但我在對象生命周期方面遇到了困難。 rustc
告訴我,我的view
函數中的self
需要'static
生命周期要求”,但我不知道如何實現。 我怎樣才能滿足這個終身要求?
error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
pub struct App {
state: State,
}
pub struct State {
pub players: Vec<Player>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Player {
pub name: String,
pub score: usize,
pub is_active: bool,
}
impl Component for App {
//... Omitted some boilerplate code for create and update
fn view(&self, ctx: &Context<Self>) -> Html {
// This gives us a component's "`Scope`" which allows us to send messages, etc to the component.
let link = ctx.link();
html! {
<div>
<button onclick={link.callback(|_| Msg::AddOne)}>{ "+1" }</button>
<div id="players">
{
self.state.players.iter().map(|p| {
html!{
<div key={p.name.as_str()}>
<input
type="checkbox"
class="toggle"
checked={p.is_active}
onclick={link.callback(move |_| Msg::Toggle(p.name))}
/>
{ format!("Hello, I'am {}!",p.name) }</div>
}
}).collect::<Html>()
}
</div>
</div>
}
}
}
完整的診斷信息:
error[E0759]: `self` has an anonymous lifetime `'_` but it needs to satisfy a `'static` lifetime requirement
--> src/main.rs:69:40
|
60 | fn view(&self, ctx: &Context<Self>) -> Html {
| ----- this data with an anonymous lifetime `'_`...
...
69 | self.state.players.iter().map(|p| {
| ------------------ ^^^^
| |
| ...is used here...
...
77 | onclick={link.callback(move |_| Msg::Toggle(p.name))}
| -------- ...and is required to live as long as `'static` here
|
note: `'static` lifetime requirement introduced by this bound
--> /Users/benny.gaechter/.cargo/registry/src/github.com-1ecc6299db9ec823/yew-0.20.0/src/html/component/scope.rs:144:26
|
144 | F: Fn(IN) -> M + 'static,
| ^^^^^^^
正如它在錯誤消息中所說: The argument given to .callback()
needs to be some Fn(IN) -> M + 'static
,也就是說,一個以一些IN
作為參數的函數,返回一些M
作為結果,並且作為一個整體是'static
(沒有比'static
短的生命周期)。
一個普通的函數指針是'static
,捕獲上下文的閉包也是'static
。 但是關閉move |_| Msg::Toggle(p.name)
move |_| Msg::Toggle(p.name)
捕獲p.name
,其中p
來自self.state.players
,而self.state.players
中的self
來自fn view(&self, ...)
。 view()
的參數&self
不是'static
,這就是編譯器所抱怨的:將閉包傳遞給callback()
'static
的唯一方法是讓view()
成為fn view(&'static self, ...)
。
fn view(&'static self, ...)
可能不是您想做或不能做的,但編譯器不知道。
你需要做的是讓閉包move |_| Msg::Toggle(p.name)
move |_| Msg::Toggle(p.name)
'static
通過將它從本地綁定的p
中分離出來。 .clone()
p.name
並將克隆move
到閉包中可能就足夠了。 由於克隆是一個擁有的String
,其生命周期不短於'static
,因此閉包本身變為'static
,滿足.callback()
的要求。 然而,這意味着Player::name
可以獨立於回調的內容而改變。 如果您的代碼中有這種可能性,請使用Rc
/ Arc
和.clone()
; 相同的論點:由於閉包擁有的Rc
/ Arc
是'static
,閉包本身變為'static
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.