Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is dyn A+B possible?

Tags:

rust

I have a custom socket that implements AsyncWrite and AsyncRead. I'd like to store a dyn to this socket, but I'd like to use both AsyncWrite/Read, like this:

#[derive(Clone)]
pub struct AsyncTransporter {
    stream: Arc<dyn AsyncRead + AsyncWrite>,
}  

but this is not supported.

60 |     stream: Arc<dyn AsyncRead + AsyncWrite>,
   |                     ---------   ^^^^^^^^^^ additional non-auto trait
   |                     |
   |                     first non-auto trait
   |
   = help: consider creating a new trait with all of these as super-traits and using that trait here instead: `trait NewTrait: tokio::io::AsyncRead + tokio::io::AsyncWrite {}`

If I do trait NewTrait: tokio::io::AsyncRead + tokio::io::AsyncWrite {}, how will the methods of both traits be implemented?

like image 862
Guerlando OCs Avatar asked Sep 20 '25 09:09

Guerlando OCs


1 Answers

If I do trait NewTrait: tokio::io::AsyncRead + tokio::io::AsyncWrite {}, how will the methods of both traits be implemented?

trait NewTrait: tokio::io::AsyncRead + tokio::io::AsyncWrite {} requires implementors of NewTrait to first implement AsyncRead and AsyncWrite, so if you have a type that implements NewTrait, you can count on AsyncRead and AsyncWrite's methods just being there. Thus it's not so much a question of "how will the methods of both traits be implemented", but of "how will NewTrait be implemented for an arbitrary type that implements AsyncRead and AsyncWrite and knows nothing of NewTrait?"

The response is, by providing a blanket implementation of NewTrait for all types that implement the two:

impl<T> NewTrait for T
where
    T: AsyncRead + AsyncWrite
{
}

With that implementation, any type (even one defined in another crate) that implements both AsyncRead and AsyncWrite also implements NewTrait.

like image 138
user4815162342 Avatar answered Sep 23 '25 07:09

user4815162342