Returning a generic tokio Framed

Is it possible to write a function that works along the lines of:

enum ProtAddr {
  Tcp(String),
  #[cfg(unix)]
  Uds(PathBuf)
}
pub fn connect<T>(pa: ProtAddr) -> Result<Framed<T, MyCodec>, Error> {
  match pa {
    ProtAddr::Tcp(sa) => {
      let stream = TcpStream::connect(sa).await?;
      let framed = Framed::new(stream, MyCodec::new());
    }

    #[cfg(unix)]
    ProtAddr::Uds(sa) => {
      let stream = UnixStream::connect(sa).await?;
      let framed = Framed::new(stream, MyCodec::new());
    }
  }
}

Having the protocol determined at runtime, but the return time generic at compile time feels like a no-no.

No, you can't use generics here. Use an enum instead, e.g. the Either enum in tokio-util.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.