Rust Patterns: Using traits for function overloading

impl Response {
pub fn set_body(&mut self, reader: Box<Reader + Send>) {
self.body = reader;
}
}
res.set_body(Box::new(get_reader()));
use std::io::File;

res.set_body(
Box::new(File::open(Path::new("./file.html")).unwrap())
);
use std::io::MemReader;

res.set_body(
Box::new(MemReader::new("bytes".as_bytes().to_vec()))
);
trait IntoReader {
type OutReader: Reader;

fn into_reader(self) -> Self::OutReader;
}
impl Response {
pub fn set_body<I>(&mut self, data: I)
where I: IntoReader, I::OutReader: Send {
self.body = Box::new(data.into_reader());
}
}
use std::io::MemReader;

impl IntoReader for String {
type OutReader = MemReader;

fn into_reader(self) -> MemReader {
MemReader::new(self.into_bytes())
}
}

impl IntoReader for Path {
type OutReader = File;

fn into_reader(self) -> File {
File::open(self).unwrap()
}
}

// Some more impls for Vec<u8>, &str, &[u8], Box<Reader> etc.
res.set_body(reader);
res.set_body(Path::new("./file.html"));
res.set_body(data);

--

--

Software Engineer by day, looking for work in Rust at night

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jonathan Reem

Jonathan Reem

165 Followers

Software Engineer by day, looking for work in Rust at night