Skip to content

Instantly share code, notes, and snippets.

@sullyj3
Created November 24, 2024 03:48
Show Gist options
  • Save sullyj3/2e3986d0b4a8eb2e3bcfb6c0e03544ba to your computer and use it in GitHub Desktop.
Save sullyj3/2e3986d0b4a8eb2e3bcfb6c0e03544ba to your computer and use it in GitHub Desktop.
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