// I'm opting for `&mut self` here as it's more general
// but this might not be necessary for your use case
trait Calculate<T, U> {
fn calculate(&mut self, t: T) -> U;
}
// Because `Fn: FnMut` this will also implement `Calculate` for `Fn`.
impl<F, T, U> Calculate<T, U> for F
where F: FnMut(T) -> U {
fn calculate(&mut self, t: T) -> U {
(self)(t)
}
}
struct State {
flag: bool,
}
impl<T, U> Calculate<T, U> for State
where T: Into<U> {
fn calculate(&mut self, t: T) -> U {
self.flag = true;
// or whatever calculation you actually need to do here
t.into()
}
}
1条答案
按热度按时间66bbxpm51#
你不能(yet)自己在稳定的Rust上实现Fn特性,你应该定义自己的特性来进行计算,然后你可以为你的结构体和任何实现Fn(或FnMut)的类型实现这些特性: