Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Example trait
- trait MyTrait {
- fn foo(&self);
- }
- // Implementations of the trait for (i32, i32) and "str"
- type MyType = (i32, i32);
- impl MyTrait for MyType {
- fn foo(&self) {
- println!("{} {}", self.0, self.1);
- }
- }
- impl MyTrait for &'static str {
- fn foo(&self) {
- println!("{}", self);
- }
- }
- // Actual example how to avoid repeating Box::new or add_item()
- fn show_all(mt: Vec<&dyn MyTrait>) {
- // List original
- for ref item in &mt {
- item.foo();
- }
- // Box all
- let mut boxed = Vec::new();
- for ref item in &mt {
- boxed.push(Box::new(*item));
- }
- // List boxed
- for ref item in &boxed {
- item.foo();
- }
- }
- // How to invoke.
- fn main() {
- show_all(vec![
- &"test",
- &(1, 2),
- &"blah",
- &(5, 7),
- ]);
- }
Add Comment
Please, Sign In to add comment