[英]What is the idiomatic way in rust for a function accepts a closure as argument or return a closure?
[英]Return a closure returning the function argument in Rust
我正在尝试编写一个函数,该函数将采用 T 类型的参数并返回一个闭包,该闭包在调用时将返回该参数。 我该怎么写?
pub struct ParseError {}
pub type Parser<T> = Box<dyn Fn(&str) -> Result<(&str, T), ParseError>>;
pub fn pure<T: 'static>(value: T) -> Parser<T> {
Box::new(move |input: &str| -> Result<(&str, T), ParseError> { Ok((input, value)) })
}
错误:
Checking parsec v0.1.0 (/home/arjaz/Documents/code/rust/parsec)
error[E0507]: cannot move out of `value`, a captured variable in an `Fn` closure
--> src/parsec.rs:16:79
|
12 | pub fn pure<T: 'static>(value: T) -> Parser<T>
| ----- captured outer variable
...
16 | Box::new(move |input: &str| -> Result<(&str, T), ParseError> { Ok((input, value)) })
| ^^^^^ move occurs because `value` has type `T`, which does not implement the `Copy` trait
error: aborting due to previous error
For more information about this error, try `rustc --explain E0507`.
error: could not compile `parsec`.
这是Rust playground 中的一个简化版本,它避免了 Box 和 Parser。 该函数消耗value
,并返回一个闭包,当调用时,它只返回value
。 请注意,闭包是FnOnce
类型(或者更准确地说,是基于FnOnce
的某种类型),因此我们只能调用它一次。 调用后,与value
关联的内存属于调用者。
相反,如果我们使用Fn
,则可以多次调用闭包。 但是在第一次调用之后,闭包不再拥有value
——它作为返回值提供给第一个调用者——所以第二次调用闭包是行不通的。 因此错误。 如果一个闭包要多次返回该值,那么它必须返回一个value
的副本或克隆,为自己保留原始的所有权。 由于该函数对value
的类型T
是通用的,因此您需要将T
约束为Copy
或Clone
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.