我正试图从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,它就会编译,但是请求不会运行。♂️
发布于 2019-08-19 15:07:37
ComponentLink::send_back()期望一个Fn闭包。但是,您的闭包正在使用一个捕获的变量,即error_msg,因此只能调用它一次。这使得闭包实现了FnOnce而不是Fn,因此不能在那里使用它。
一个更简单的方法是:
struct Foo;
fn call(f: impl Fn() -> Foo) {}
fn test(x: Foo) {
let cb = move || x;
call(cb);
}完整的错误信息比较清楚:
error[E0525]: expected a closure that implements the `Fn` trait, but this closure only implements `FnOnce`
--> src/lib.rs:6:14
|
6 | let cb = move || x;
| ^^^^^^^^-
| | |
| | closure is `FnOnce` because it moves the variable `x` out of its environment
| this closure implements `FnOnce`, not `Fn`
7 | call(cb);
| ---- the requirement to implement `Fn` derives from here这是有道理的;如果您多次编写call(cb),会发生什么?记住,Foo是不可复制的,也不是可复制的。
准确地说,最简单的解决方案是使您的类型可以复制,这样就可以重用它:
let cb = move || {
x.clone()
};而且起作用了!
如果不想要克隆的成本,可以添加一些变通方法,例如传递返回错误的函数或某种引用计数指针。例如:
struct Foo;
fn call(f: impl Fn() -> Foo) {}
fn test(build_x: impl Fn() -> Foo) {
let cb = move || build_x();
call(cb);
}这是因为build_x是一个Fn,而不是一个FnOnce,所以它在使用时不会被消耗,也就是说,您可以任意多次调用它。
另一个没有回调的解决方法是使用Option并使用Option::take来使用它。这将它替换为None,并且从借贷检查器的角度来看,这个值仍然存在。但是,您需要一个RefCell,因为否则您将变异捕获的变量并将闭包转换为FnMut。
use std::cell::RefCell;
struct Foo;
fn call(f: impl Fn() -> Foo) {}
fn test(x: Foo) {
let ox = RefCell::new(Some(x));
let cb = move || ox.borrow_mut().take().unwrap();
call(cb);
}更新到最后一个选项
当一个简单的RefCell将完成时,不要使用Cell。Cell有一个take成员函数,使代码更简单:
use std::cell::Cell;
struct Foo;
fn call(f: impl Fn() -> Foo) {}
fn test(x: Foo) {
let ox = Cell::new(Some(x));
let cb = move || ox.take().unwrap();
call(cb);
}https://stackoverflow.com/questions/57549813
复制相似问题