Created
November 24, 2024 03:48
-
-
Save sullyj3/2e3986d0b4a8eb2e3bcfb6c0e03544ba to your computer and use it in GitHub Desktop.
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
fn main() { | |
let xs: Vec<Box<dyn PrintableNumber>> = vec![Box::new(Foo), Box::new(Bar)]; | |
print_each(xs); | |
} | |
struct Foo; | |
struct Bar; | |
// Combined trait that requires both ToString and ToInt | |
trait PrintableNumber: ToString + ToInt {} | |
// Implement the combined trait for any type that implements both component traits | |
impl<T: ToString + ToInt> PrintableNumber for T {} | |
trait ToString { | |
fn to_string(&self) -> String; | |
} | |
impl ToString for Foo { | |
fn to_string(&self) -> String { | |
"Foo".to_string() | |
} | |
} | |
impl ToString for Bar { | |
fn to_string(&self) -> String { | |
"Bar".to_string() | |
} | |
} | |
trait ToInt { | |
fn to_int(&self) -> i32; | |
} | |
impl ToInt for Foo { | |
fn to_int(&self) -> i32 { | |
42 | |
} | |
} | |
impl ToInt for Bar { | |
fn to_int(&self) -> i32 { | |
24 | |
} | |
} | |
fn print_each(xs: Vec<Box<dyn PrintableNumber>>) { | |
for x in xs { | |
println!("{}", x.to_string()); | |
println!("{}", x.to_int()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment