3

I have a generic function that operates on several different structs. On of these structs looks like this:

struct A {
    data: Vec<String>
}

When I try to use dbg! or println!("{:?}", my_instance), I get this error:

`T` cannot be formatted using `{:?}` because it doesn't implement `Debug`

I understand I need to write my own Debug impl, but I don't understand how to do that for vectors. How can I get my struct to just print? I can not figure it out. I've been trying to do something like this:

impl std::fmt::Debug for Datum {
    fn fmt(&self) -> String {
        format!("{:?}", self)
    }
}
turtle
  • 7,533
  • 18
  • 68
  • 97
  • 2
    Summarizing the other answers: just add `#[derive(Debug)]` to your struct to get the default formatting. – trent Sep 16 '20 at 21:08
  • 1
    Could also be [How to implement a custom 'fmt::Debug' trait?](/q/22243527/3650362) if the default formatting isn't what you want. – trent Sep 16 '20 at 21:11
  • No, `#[derive(Debug)]` does not work. My issue (I think), is I don't know to get debug working for vectors. – turtle Sep 16 '20 at 21:29
  • [It does though](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=2d2736b63c77f6efed56d949dfc7b5b0). You don't have to do anything special to implement `Debug` for `Vec`; it's already implemented (in every case where it can be; that is, when `T: Debug`). – trent Sep 16 '20 at 22:17
  • thanks. yes, i understand, but i can't print my instance. the error says T doesn't implement Debug, but I have `#[derive(Debug)]` on the struct. why is this? – turtle Sep 16 '20 at 22:23
  • 1
    Hard to say, since I don't have your code in front of me. Maybe you need to add a `T: Debug` bound somewhere? – trent Sep 17 '20 at 01:08
  • thanks again. you are correct. the only way i was able to get it to work was to add `T: Debug + MyTrait>` – turtle Sep 17 '20 at 11:02

0 Answers0