My goal is printing the contents of struct that has trait object member but I can't find how to tell Rust compiler that the member also implements other traits like Display
or Debug
.
For example, in the following program, I want to print the structure of S2
(and S1
for comparison) but I get stuck in the implementation of fmt
.
trait Tr {}
impl Tr for usize {}
impl Tr for String {}
#[derive(Debug)]
struct S1<A: Tr + std::fmt::Debug> {
member: Box<A>,
}
struct S2 {
member: Box<Tr>,
}
impl std::fmt::Debug for S2 {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
// ??
Ok(())
}
}
fn main() {
let s1 = S1 {
member: Box::new(String::from("abc")),
};
println!("{:?}", s1);
let s2 = S2 {
member: Box::new(String::from("abc")),
};
println!("{:?}", s2);
}
My desired output of this program is
S1 { member: "abc" }
S2 { member: "abc" }
Is it possible to implement Debug
for a struct like S2
?
(Rust version: 1.35)