How do I print a struct when the type doesn’t implement Debug or Display?

Hi, I’m new to Rust. I have a struct that contains a field from another module/crate. For example:

struct Subscription {
    status: SubscriptionInfo, // this type comes from another module
    loading: bool,
}

The problem is that SubscriptionInfo does not implement the Debug or Display traits. Because of that, I can’t use println!("{:?}", ...) or println!("{}", ...) on Subscription even if i add the derive attribute above Subscription.

What’s the recommended way to print if I can’t modify the definition of SubscriptionInfo?

Assuming your goal is to print a Subscription, what exactly do you want displayed for the status field?

2 Likes

I want to display all the fields of the struct, including strings, vectors, and an enum. Thanks for replying!

I've done things like

struct LocalDebug<T>(T);

impl fmt::Debug for LocalDebug<&SubscriptionInfo> { ... }

impl fmt::Debug for Subscription {
    fn fmt(&self, fmtr: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmtr.debug_struct("Subscription")
            .field("status", &LocalDebug(&self.status))
            .field("loading", &self.loading)
            .finish()
    }
}
2 Likes

Your first problem is that the structure and its fields are not public. As defined, it cannot be accessed from another crate; the first thing you need to do is make it public. It also does not implement Serialize, which could be used to serialize it into JSON first and print that (it is human readable).

If you are really stuck on something, you can fork the repository, check it out and instruct your Cargo.toml to use this local folder:

package_with_struct = { path = "../package_with_struct" }

This way you get access to the code and can add #[derive(Debug)] to Subscription and another to SubscriptionInfo. You can also add print statements. After you have finished working on the issue, revert the Cargo.toml file to use the original package.

While forking packages for permanent use has many drawbacks and should most often not be done, I see nothing wrong with looking into the code of any open source package and experimenting with it.

1 Like

That's a really great explanation. Thank you so much.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.