Implement something like fmt::Display trait with data

I am trying to make a C++ code generator for a small project, and I was trying to mimic something like fmt::Display.

Here is a short snippet of where I was going with it:

pub trait CodeGenerate {
    fn generate(&self, f: &mut fmt::Formatter<'_>, info: CodeGenerationInfo) -> fmt::Result;
}

My plan was then to have the impl of CodeGenerate recursively call generate() on the heirarchy of code parts, and use write!() to write to the formatter f sort of how the impl of fmt::Display does.

The reason I cannot use fmt::Display directly is that my generate function takes a CodeGenerationInfo parameter to provide context for the generation as well as the guidelines for how to generate the code.

I was wanting to be able to use functions like println!() and format!() with my CodeGenerate trait somehow, but I am not seeing any way to do that with the required information from CodeGenerationInfo

I am a bit of a rust noob, so this may be very obvious. Any help would be greatly appreciated.

Perhaps you want to implement Display for something that wraps implementors of CodeGenerate and CodeGenerationInfo:

3 Likes

That is exactly what I was looking for. Thank you :smiley: