如果您引用闭包,这是可能的,因为您可以Copy
参考。
一般来说,克隆封闭是不可能的。但是,您可以创建一个包含函数使用的变量的结构类型,派生Clone
就可以了,然后执行Fn
自己做吧。
引用闭包的示例:
// The parser type needs to be sized if we want to be able to make maps.
trait Parser<A>: Sized {
// Cannot have the ": Clone" bound because of `Map`.
// Every parser needs to have a `run` function that takes the input as argument
// and optionally produces a result and the remaining input.
fn run(&self, input: &str) -> Option<(A, String)>;
fn map<B>(self, f: &Fn(A) -> B) -> Map<A, B, Self> {
Map {
parser: self,
map_function: f,
}
}
}
struct Char {
chr: char,
}
impl Parser<char> for Char {
// These days it is more complicated than in 2014 to find the first
// character of a string. I don't know how to easily return the subslice
// that skips the first character. Returning a `String` is a wasteful way
// to structure a parser in Rust.
fn run(&self, input: &str) -> Option<(char, String)> {
if !input.is_empty() {
let mut chars = input.chars();
let first: char = chars.next().unwrap();
if input.len() > 0 && first == self.chr {
let rest: String = chars.collect();
Some((self.chr, rest))
} else {
None
}
} else {
None
}
}
}
struct Map<'a, A: 'a, B: 'a, PA> {
parser: PA,
map_function: &'a Fn(A) -> B,
}
impl<'a, A, B, PA: Parser<A>> Parser<B> for Map<'a, A, B, PA> {
fn run(&self, input: &str) -> Option<(B, String)> {
let (a, rest) = self.parser.run(input)?;
Some(((self.map_function)(a), rest))
}
}
fn main() {
let parser = Char { chr: '5' };
let result_1 = parser.run(&"567");
let base = 10;
let closure = |c: char| c.to_digit(base).unwrap();
assert!(result_1 == Some(('5', "67".to_string())));
let map_parser = parser.map(&closure);
let result_2 = map_parser.run(&"567");
assert!(result_2 == Some((5, "67".to_string())));
}