Skip to content

Instantly share code, notes, and snippets.

Created April 25, 2016 19:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/fff6f301b00e03d04e46332f4992e722 to your computer and use it in GitHub Desktop.
Save anonymous/fff6f301b00e03d04e46332f4992e722 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
// The traits in question.
trait Read {
fn read(&self);
}
trait Write {
fn write(&mut self);
}
// Only those types may implement ReadWrite
// that implement both Read and Write.
trait ReadWrite: Read + Write {}
// Our data type.
struct SomeData;
// Trait implementations.
impl Read for SomeData {
fn read(&self) {
println!("read called");
}
}
impl Write for SomeData {
fn write(&mut self) {
println!("write called");
}
}
impl ReadWrite for SomeData {}
fn read<A:Read>(x:Box<A>) -> () { x.read(); }
fn write<A:Write>(mut x:Box<A>) -> () { x.write(); }
fn main() {
// Get trait object.
let mut trait_object: Box<ReadWrite> = Box::new(SomeData);
// Implicit cast to Read.
read(trait_object);
// Implicit cast to Write.
write(trait_object);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment