我试图弄清楚如何从 yew 示例中使这个 Web 请求代码通用反序列化类型和枚举的变体。
// Deserialize type
#[derive(Debug, Deserialize)]
pub struct TagsResponse {
tags: Vec<String>,
}
// Enum variants
pub enum Msg {
TagsLoaded(Result<TagsResponse, Error>),
TagsLoadError,
}
// Working non-generic inline code
let callback = model.link.send_back(
// want to make TagsResponse generic ⤵
move |response: Response<Json<Result<TagsResponse, Error>>>| {
let (meta, Json(data)) = response.into_parts();
if meta.status.is_success() {
// ↓ and be able to pass in an enum value
Msg::TagsLoaded(data)
} else {
// ↓ and be able to pass in an enum value
Msg::TagsLoadError
}
},
);
let request = Request::get(format!("{}{}", API_ULR, "tags"))
.body(Nothing)
.unwrap();
let task = model.fetch_service.fetch(request, callback);
model.fetch_task.push(task);
据我所知,这似乎非常接近,但我在编译器之后陷入了一种循环:
fn remote_get<T: 'static>(
fetch_service: &mut FetchService,
link: &mut ComponentLink<Model>,
success_msg: fn(Result<T, Error>) -> Msg,
error_msg: Msg,
) -> FetchTask
where
for<'de> T: serde::Deserialize<'de>,
{
let callback = link.send_back(move |response: Response<Json<Result<T, Error>>>| {
let (meta, Json(data)) = response.into_parts();
if meta.status.is_success() {
success_msg(data)
} else {
error_msg
}
});
let request = Request::get(format!("{}{}", API_ULR, "articles?limit=10&offset=0"))
.body(Nothing)
.unwrap();
fetch_service.fetch(request, callback)
}
与呼叫站点:
let task = remote_get(
&mut self.fetch_service,
&mut self.link,
Msg::TagsLoaded,
Msg::TagsLoadError,
);
self.fetch_task.push(task);
产生:
|
598 | error_msg: Msg,
| --------- captured outer variable
...
608 | error_msg
| ^^^^^^^^^ cannot move out of captured variable in an `Fn` closure
奇怪的是,如果我从参数列表中删除 error_msg 并简单地进行硬编码Msg::TagsLoadError
,它将编译但请求不会运行。♂️</p>