1

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 Answer 1

3

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 {}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.