Created
April 25, 2016 19:39
-
-
Save anonymous/fff6f301b00e03d04e46332f4992e722 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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