I'm learning Rust and have encountered a vexing issue involving closures. I've gotten a lot of the basic closure examples to work, but now that I've stepped out of the basic "make adder" and "call on" examples, things are getting messy. This is the first part of my code, which works:
trait TransformationElt<T, F> where F: Fn(T) -> T {
fn get_transform(&self) -> Box<F>;
}
pub struct AddSome { pub x: i64 }
impl AddSome {
fn the_transform(&self) -> Box<Fn(i64) -> i64> {
Box::new(|x: i64| x + 1 as i64)
}
}
This successfully returns a heap-allocated closure that adds 1, implementing our AddSome
type. I want AddSome
to implement TransformationElt
, specifically for the type i64
:
impl<F: Fn(i64) -> i64> TransformationElt<i64, F> for AddSome {
fn get_transform(&self) -> Box<F> {
Box::new(move |x: i64| x + self.x as i64)
}
}
After much hackery and trying different things, I still can't get it to compile. The error I typically get is:
src/lex/math/algebra/groups.rs:31:16: 31:46 error: mismatched types: expected
F
, found[closure@src/lex/math/algebra/groups.rs:31:16: 31:46 self:_]
(expected type parameter, found closure) [E0308]
How do I get around this seemingly basic issue and implement my "transform" type?
One final thing -- I have reasons I want to keep things as closures. I intend to compose them, etc. etc., things where I really do need higher-order functions.