Hi All,
I'm trying to write a function that would take in a bool and based on its value, return an object. I'm using bool for simplicity but I plan on using an enum to add more types later.
use std::net::TcpStream;
use std::fs::File;
//any other structs that implement io::read and io::write
trait Transmit: std::marker::Sync + std::marker::Send {
fn transmit(&self, String);
}
struct Comm<S> {
stream: Option<S>,
}
impl<S: 'static + std::marker::Send + std::marker::Sync> Comm<S>
where
S: std::io::Read + std::io::Write,
{
fn new(s: S) -> Self {
Comm { stream: Some(s) }
}
}
impl<S: 'static + std::marker::Send + std::marker::Sync> Transmit for Comm<S>
where
S: std::io::Read + std::io::Write,
{
fn transmit(&mut self, buf: &str) {
//What to do here?
self.stream.unwrap().write_all(buf.as_bytes());
}
}
//what can be the return type of Comm here?
//all i want to do is return an object that satisfies
//the traits std::io::Read and std::io::Write
fn build(dst:&str, f: bool) -> Comm/*<?>*/ {
if f {
let _f = File::create(dst).unwrap();
let _fs = Comm::<File>::new(_f);
} else {
let _t = TcpStream::connect(dst).unwrap();
let _ts = Comm::<TcpStream>::new(_t);
}
}
fn main() {
//what is the type of _vec here?
let _vec = Vec::new();
_vec.push(build("google.com",false));
_vec.push(build("./abc.txt",true));
for _s in _vec {
_s.transmit("hello");
}
}
What am I doing wrong here? What am I missing for build
's return type? Is there a better way to achieve this?