Rust / Prost : How do add Debug to structs & unions?

1.3k Views Asked by At

It looks like the prost protobuf generator only adds derive(Debug) to generated enum types (and only enums not inside a pub mod block). None of the generated structs, or unions have it applied. How can I get prost to add it to everything?

Using Prost version 0.9 and rustic 1.56

2

There are 2 best solutions below

1
West_JR On BEST ANSWER

Prost does derive Debug on everything. But you need prost::Messaeg in scope or you'll get an error about missing Debug traits.

2
Hadus On

prost doesn't have an option to turn that on so you have to do it yourself.

If you want to implement a trait for a type. You need to have either the trait or the type in your library/binary.

Since the trait is in std and the type is in an external crate the best you can do is create a unit struct to wrap the type. Then implement Debug for that.

use std::fmt;

struct DebugStruct(NonDebugEnum);

impl fmt::Debug for DebugStruct {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        todo!()
    }
}

fn main() {
    let wrapped = DebugStruct(NonDebugEnum::Example);
    println!("{:?}", wrapped);
}

You will have to come up with the actual logic of how to format it.