housleyjk / ws-rs

Lightweight, event-driven WebSockets for Rust.
MIT License
1.46k stars 219 forks source link

How to return a ws::Handler trait object by the `factory` param of ws::connect? #324

Open ngugc opened 4 years ago

ngugc commented 4 years ago
    pub fn connect<U, F, H>(url: U, factory: F) -> Result<()> 
    where
        U: Borrow<str>,
        F: FnMut(Sender) -> H,
        H: Handler, 

This is the signature of ws::connect. A ws::Handler trait object should be returned by F. I have the following implementations of ws::Handler.

    struct A { ... }
    impl ws::Handler for A {}

    struct B { ... }
    impl ws::Handler for B {}

    fn new_ws(t: &String) -> Box<dyn ws::Handler> {
        match t {
            "A" => Box::new(A { ... }),
            "B" => Box::new(B { ... }),
            &_ => unimplemented!(),
        }
    }

How can I use new_ws in ws::connect as below?

    ws::connect(URL, |sender| {
        new_ws("A")
    }).unwrap_or_else(|err| {
        error!("websocket error: {:?}", err);
    })

The error:

expected an `Fn<(ws::message::Message,)>` closure, found `dyn ws::handler::Handler

Thanks!