Best-Practises: implement Display in library

Hello everyone

I’m learning Rust by writing a little CLI application which is split in a library- and application-part. The library is currently returning some struct to the application and I wanted to implement Display within the application.
Unfortunately this is not possible because, for good reason, you are only allowed to implement traits for structs which reside in the current crate. My library and application though are distinct crates (lib.rs and /bin/app.rs).

Now I could implement Display for the struct within the library which of course isn’t a big deal, but I am interested in other best-practices: how can I separate user-facing functionality from the library?

Thx.

You could write a newtype that defines the application's display format:

struct LogDisplay<'a, T>(&'a T);
struct ReportDisplay<'a, T>(&'a T);

impl<'a> Display for LogDisplay<'a, LibraryStruct1> { ... }
impl<'a,T> Display for LogDisplay<'a, LibraryStruct2<T>> { ... }

impl<'a> Display for ReportDisplay<'a, LibraryStruct1> { ... }
impl<'a,T> Display for ReportDisplay<'a, LibraryStruct2<T>> { ... }

fn log<T>(x:&'_ T) where LogDisplay<'_,T>: Display {
    eprintln!("{:?}\t{}", std::time::Instant::now(), LogDisplay(x));
}
3 Likes

I just gave it a try and it works as I need. Thanks a lot