0
votes

I want to print the instance of Tweet datatype in main function, but the summary trait don't implement the debug trait. Is there any way to implement a trait on trait or any work around. uncommentating the second line and commentating the first line would work because String type implements the Display trait.

#[derive(Debug)]
struct Tweet {
    name: String,
}

pub trait Summary {
    fn summarize(&self) -> String;
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("@{}", &self.name)
    }
}

fn summarizeable(x: String) -> impl Summary {
    Tweet { name: x }
}

fn main() {
    //1.
    println!("{:#?}", summarizeable(String::from("Alex")));
    //2.println!("{}",summarizeable(String::from("Alex")).summarize());
}

error[E0277]: impl Summary doesn't implement std::fmt::Debug --> src/main.rs:26:29 | 26 | /1./ println!("{:#?}",summarizeable(String::from("Alex"))); |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ impl Summary cannot be formatted using {:?} because it doesn't implement std::fmt::Debug | = help: the trait std::fmt::Debug is not implemented for impl Summary = note: required by std::fmt::Debug::fmt

error: aborting due to previous error

For more information about this error, try rustc --explain E0277. error: Could not compile p1.

To learn more, run the command again with --verbose.

1

1 Answers

1
votes

You can require that anything that impls Summary must also impl std::fmt::Debug as follows:

pub trait Summary : std::fmt::Debug { // Summary requires Debug
    fn summarize(&self) -> String;
}

If you do not want to tie Debug to Summary you can always introduce another trait subsuming the other two:

pub trait DebuggableSummary : Summary + std::fmt::Display {}