Can I get a trait object of a multi-trait instance without using a generic type?

后端 未结 1 1580
我在风中等你
我在风中等你 2020-12-06 17:03

I am trying to get a dynamically dispatchable borrow to an instance of an object implementing both Reader and Seek.

I understand that Rust

相关标签:
1条回答
  • 2020-12-06 17:30

    You can create an empty trait that merges those two traits:

    use std::io::{Read, Seek};
    
    trait SeekRead: Seek + Read {}
    impl<T: Seek + Read> SeekRead for T {}
    
    fn user_dynamic(stream: &mut SeekRead) {}
    

    This will create a new vtable for SeekRead that contains all the function pointers of both Seek and Read.

    You will not be able to cast your &mut SeekRead to either &mut Seek or &mut Read without some trickery (see Why doesn't Rust support trait object upcasting?)

    0 讨论(0)
提交回复
热议问题