简体   繁体   中英

how can I implement an external trait on an internal trait in Rust?

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.

You can require that anything that impl s 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 {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM