Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rust generic traits
// Parameter that each resolver accepts.
pub struct Intent {}
// Resolver definition.
pub trait Resolver {
fn resolve(&self, intent: Intent) -> Result<usize, usize>;
}
impl<F: Fn(Intent) -> Result<usize, usize>> Resolver for F {
fn resolve(&self, intent: Intent) -> Result<usize, usize> {
self(intent)
}
}
// Application holding resolver of type struct or function pointer.
struct App<'a> {
pub resolver: Option<&'a dyn Resolver>,
}
impl <'a> App<'a> {
fn with_resolver(&mut self, resolver: &'a dyn Resolver) {
self.resolver = Some(resolver);
}
pub fn resolve(&self) {
let handler = self.resolver.unwrap();
let res = handler.resolve(Intent{});
println!("XXXXX: {:?}", res.unwrap())
}
}
// Run app with two different resolvers.
fn main() {
let mut command = App { resolver: None };
// set structure
struct Foo {}
impl Resolver for Foo {
fn resolve(&self, _: Intent) -> Result<usize, usize> { Ok(2) }
}
command.with_resolver(&Foo{});
command.resolve();
// or set function pointer / closure
fn bar(_: Intent) -> Result<usize, usize> { Ok(3) }
command.with_resolver(&bar);
command.resolve();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment