Clone a closure preserving structure

I'm currently trying to implement a simple Parser-Combinator library in Rust. For this, I would like to have a generic map function to convert the result of the analyzer.

The problem is that I do not know how to copy a structure with a closure. An example is the map structure in the following example. It has a mapFunction field that stores a function that receives the result of the previous analyzer and returns a new result. map itself is a parser that can be further combined with other parsers.

However, for parsers that need to be combined, I would need to copy them (having a binding to Clone ), but how to do this for map ?

Example: (Only pseudo code will most likely not compile)

 trait Parser<A> { // 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, ~str)> } struct Char { chr: char } impl Parser<char> for Char { // The char parser returns Some(char) if the first fn run(&self, input: ~str) -> Option<(char, ~str)> { if input.len() > 0 && input[0] == self.chr { Some((self.chr, input.slice(1, input.len()))) } else { None } } } struct Map<'a, A, B, PA> { parser: PA, mapFunction: 'a |result: A| -> B, } impl<'a, A, B, PA: Parser<A>> Parser<B> for Map<'a, A, B, PA> { fn run(&self, input: ~str) -> Option<(B, ~str)> { ... } } fn main() { let parser = Char{ chr: 'a' }; let result = parser.run(~"abc"); // let mapParser = parser.map(|c: char| atoi(c)); assert!(result == Some('a')); } 
+7
source share

No one has answered this question yet.

See similar questions:

12
Can you clone a closure?
3
Cloning std :: iter :: Map with the deduced (?) Type
2
Borrow when closing the filter is not long enough

or similar:

84
Move against copy in rust
eleven
Encapsulating a Sequentially Initialized State with Self-Advertising in the Rust Structure
6
What are the actual time it takes to execute a dynamic dispatch?
3
Using Trait types with rust-portaudio in non-blocking mode
2
The problem of borrowing rust with getter method on the structure
2
Is there a way to let Rust infer the correct type for the associated type?
2
"expected associated lifetime parameter" when trying to call a generic function
0
the map method cannot be called on an Iterator <t> attribute object
0
Show output in the general structure
0
The function referenced from the one stored in the structure does not give up ownership

All Articles