Rust doesn’t have function or method overloading built in, but you can use the extremely flexible trait system to get something very much like it.

Let’s imagine we are writing a simple HTTP server framework and we’d like to expose a method on our Response representation to set the body of the response. Since our Response stores the body as a Reader trait object, we can just write a simple method which accepts a Reader:

impl Response {

pub fn set_body(&mut self, reader: Box<Reader + Send>) {

self.body = reader;

}

}

That was easy — but, before we get ahead of ourselves, let’s try some typical use cases:

Reading from an arbitrary reader:

res.set_body(Box::new(get_reader()));

Reading from a file:

use std::io::File;



res.set_body(

Box::new(File::open(Path::new("./file.html")).unwrap())

);

Reading from a string literal, Vec<u8>, or String:

use std::io::MemReader;



res.set_body(

Box::new(MemReader::new("bytes".as_bytes().to_vec()))

);

It doesn’t take a lot of playing around to see that our API is incredibly verbose to use and unergonomic in several common cases — we can do better.