How to use a tag object to reference a structure that has common methods

In connection with this issue, While preserving the closure in HashMap , I learned that the correct passage of closures on a function requires that the function be general and accept any type that implements the Fn, FnMut, or FnOnce function.

When implementing part of a library from C ++ as a training exercise, I need a type of abstraction like this.

use std::collections::HashMap;

struct Event;

trait IObject {
    fn makeFunc<F : FnMut(&Event)>(&mut self, s : &str, f : F);
}

struct Object1<'a> {
    m_funcs : HashMap<String, Box<FnMut(&Event) + 'a>>
}

impl <'a> Object1<'a> {
    fn new() -> Object1<'a> {
        Object1 {m_funcs : HashMap::new()}
    }
}

impl <'a> IObject for Object1<'a> {
    fn makeFunc<F : FnMut(&Event) + 'a>(&mut self, s: &str, f: F) {
        self.m_funcs.insert(String::from_str(s), Box::new(f));
    }
}

fn main() {
    let obj : &IObject = &Object1::new();
    println!("Hello, world!");
}

However, the returned error indicates that IObject cannot be a sign object, since it contains a method with common parameters. However, to completely close the function of a function, I need generics. Can someone show me how to achieve the abstraction I'm looking for, but can still go through the closure of functions?

+4
1

; . , (generics) vtable, (-).

: IObject -, Box<FnMut(&Event) + 'a>.

, , IObject - F, . 'a ( ).

+5

All Articles