Re:Rust is more than safety
by mmstick on Wednesday December 28, 2016 @05:22PM
(#13274203)
Here's an example: `Stdin` and `File` both implement the `Read` trait. Therefore, you can write a function that takes the traits that you want to use as input parameters.
fn do_something_with<S: Read>(source: S) {
// do something with input source
}
Then you can do the following:
let stdout = io::stdout();
do_something_with(stdout.lock());
let file = File::open(path).unwrap();
do_something_with(file);
You're free to narrow down/expand the types/methods that can be used with the function if you add more traits.
fn do_something_with<S: Read>(source: S) {
}Then you can do the following:
let stdout = io::stdout();
do_something_with(stdout.lock());
let file = File::open(path).unwrap();
do_something_with(file);
You're free to narrow down/expand the types/methods that can be used with the function if you add more traits.