预期"FnMut< (X< & # 39; _>),在"关闭,发

  • 本文关键字:quot 关闭 FnMut 预期 rust
  • 更新时间 :
  • 英文 :


我实现了一个trait来在我的结构之间共享类似的逻辑。该特性提供了一个collect_responses函数,该函数接受处理程序的向量,并返回处理程序的响应向量。我无法编译我的代码,因为我得到了一个错误:

error[E0277]: expected a `FnMut<(HandlerInput<'_>,)>` closure, found `dyn for<'r, 's> FnMut(&'r 
mut HandlerInput<'s>) -> Result<HandlerOutput, std::io::Error>`
--> src/lib.rs:146:18
|
146 |             self.process(handler, vec![]);
|                  ^^^^^^^ expected an `FnMut<(HandlerInput<'_>,)>` closure, found `dyn for<'r, 's> FnMut(&'r mut HandlerInput<'s>) -> Result<HandlerOutput, std::io::Error>`
|
= help: the trait `FnMut<(HandlerInput<'_>,)>` is not implemented for `dyn for<'r, 's> 
FnMut(&'r mut HandlerInput<'s>) -> Result<HandlerOutput, std::io::Error>`
= note: expected a closure with arguments `(&mut HandlerInput<'_>,)`
found a closure with arguments `(HandlerInput<'_>,)`
= note: required because of the requirement

这是我实际代码中的沙盒示例。

这是trait代码:

pub trait Processor {
fn process_input(input: HandlerInput) -> Result<Vec<HandlerOutput>, Error>;
fn collect_responses(
handlers: Vec<Box<dyn FnMut(&mut HandlerInput) -> Result<HandlerOutput, Error>>>,
input: HandlerInput
) -> Result<Vec<HandlerOutput>, Error> {
let responses = handlers
.iter()
.map(|func| func(&mut input))
.filter(|r| match r {
Ok(_) => true,
_ => false,
})
.map(|r| r.unwrap())
.collect::<Vec<HandlerOutput>>();
return if responses.is_empty() {
Err(
Error::new(
ErrorKind::Other,
"No successful response"
)
)
} else {
Ok(responses)
}
}
}

这是在代码中我得到一个错误的地方:

fn process<F>(&mut self, handler: F, data: Vec<u8>)
where
F: FnMut(HandlerInput) -> Result<HandlerOutput, Error>
{
let response: Result<HandlerOutput, Error> = handler(HandlerInput {
session: &mut self.session,
data: Some(data),
});
match response.unwrap() {
HandlerOutput::Data(result) => {
self.handle_write(result).unwrap();
},
HandlerOutput::ConnectionRequest(host, port) => {
self.connect(&host[..], port);
},
HandlerOutput::Void => {},
}
}

你能告诉我如何将处理程序正确地传递给self.process吗?

更新:这就是我如何调用process函数:

let handlers = AuthProcessor::init();
for handler in handlers {
self.process(handler, vec![]);
}

编译器会直接指向错误。你有一个基本类型的盒装闭包:

FnMut(&mut HandlerInput) -> Result<HandlerOutput, Error>

但是你想把它给一个想要:

的函数
FnMut(HandlerInput) -> Result<HandlerOutput, Error>

参数不匹配。您需要更改其中一个以匹配另一个。

相关内容

最新更新