gpt4 book ai didi

generics - 包含闭包参数的方法需要错误的类型?

转载 作者:行者123 更新时间:2023-12-03 11:43:15 31 4
gpt4 key购买 nike

我有一个结构体,Parser其中包含一个 transformer - 用于修改其 ParserState 的函数- 和说ParserState .

#[derive(Clone)]
pub struct Parser<F>
where
F: Fn(ParserState) -> ParserState
{
pub transformer: F,
pub state: ParserState
}

#[derive(Debug, PartialEq, Clone)]
pub struct ParserState {
pub target: String,
pub index: usize,
pub result: Vec<String>, // the container of eventual results from the parsing, with Some(result) or None. Should be a vetor
pub error: bool, // whether we've encountered an error; index -> 0, Some(err_msg)
pub err_msg: Option<String> // Eventual error message
}

定义 .map()方法,我假设我可以简单地使用一个闭包,并在其中引用解析器自己的状态,将其作为参数传递给该闭包。此闭包将用作 .map() 的参数方法。

impl<F> Parser<F>
where
F: Fn(ParserState) -> ParserState
{
pub fn new(f: F) -> Self {
// creating a new Parser just means deciding on which closure it applies
Parser {
transformer: f,
state: ParserState {
target: String::from(""),
index: 0,
result: vec![],
error: false,
err_msg: None
}
}
}

pub fn map<G>(&mut self, g: G) -> ()
where
G: Fn(ParserState) -> ParserState
{
self.state = g((self.state).clone())
}

pub fn run(mut self, corpus: String) -> Self {
self.state.target = corpus;
self.state = (self.transformer)(self.state);
self
}
}


我是这样使用它的:
fn main() {
let haystack: String = String::from("Hello!Goodbye!");
let needle = String::from("Hello!");
let str_parser = Parser::new(str_parser(needle));
let closure = |mut state: ParserState| state.index = 0;
let result = str_parser.run(haystack);
let result = result.map(closure);
let adv = ParserState {
target: "Hello!Goodbye!".to_string(),
index: 0,
result: vec!["Hello!".to_string()],
error: false,
err_msg: None
};
assert_eq!(adv, result.state);
}

这没有奏效。我遇到了这个错误:

error[E0271]: type mismatch resolving `<[closure@src/lib.rs:49:23: 49:63] as std::ops::FnOnce<(parse
rs::ParserState,)>>::Output == parsers::ParserState`
--> src/lib.rs:51:29
|
51 | let result = result.map(closure);
| ^^^ expected `()`, found struct `parsers::ParserState`

并且不确定如何 FnOnce ,我没有提到,是相关的。我也不明白怎么 .map()预计 ()作为参数,当它是 Parser 的方法时.我觉得这里有点超出我的深度。

这是指向 the relevant Rust playground 的链接

最佳答案

此关闭返回 () (即它不返回值):

let closure = |mut state: ParserState| state.index = 0;

但是 F声明返回 ParserState .您只需要按预期使函数返回值即可。
let closure = |mut state: ParserState| {
state.index = 0;
state
};

and am not sure how FnOnce, which I have not mentioned, is relevant.


FnOnce是最普遍的功能特征;所有函数至少可以被调用一次,所以所有函数都实现了 FnOnce ,但可能不会实现 FnFnMut .我认为它提到的事实 FnOnce在错误消息中只是它尝试匹配类型的顺序的一个工件。

关于generics - 包含闭包参数的方法需要错误的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61454558/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com