Skip to content

Comment on Rust Any part 3: we have upcastsparent

Comments

You can do something akin to QueryInterface from COM, though it's a bit verbose.

https://play.rust-lang.org/?version=beta&mode=debug&edition=... (ninja edited a few times with some improvements)

With a bit of API massaging, this could be improved quite a bit in terms of ergonomics. The challenge is that traits often require concrete structs if you want them to participate in dynamic typing.

Basically you can now make something like `Arc<dyn QueryInterface>` work, where multiple traits are available through a `query_interface`:

    fn main() {
        let x = Arc::new(X);
        let y = Arc::new(Y);
        let any = [x as Arc<dyn QueryInterface>, y as _];
        for any in any {
            if let Some(a) = any.query_interface::<dyn A>() {
                a.a();
            }
            if let Some(b) = any.query_interface::<dyn B>() {
                b.b();
            }
        }
    }
AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.