Easy lazy conditional formatting

Implement Display for Fn(f: &mut std::fmt::Formatter) -> std::fmt::Result, or: easy lazy conditional formatting.

example:

println!("    ({}, {}) {: <6} {}", first >> 4, first & 0xF, |f| { if second != 0 { write!(f, "({}, {})", second >> 4, second & 0xF)?; } Ok(()) }, count);

(okay, you’d need to use |f: &mut F| or something - or cheat a little, but w/e)

example today: https://play.rust-lang.org/?version=stable&mode=debug&edition=2015&gist=0315dab7653d771d7d777ddc06f4cef0

we currently have no nice way of doing conditional formatting stuff. there’s no impl<T> Display for Option<T> where T: Display either, for example.

anyway, just an idea.

I think this as-written would be very limiting in the future when arbitrary types can implement the Fn traits.

Why not just make a crate with a simple newtype that implements Display by calling the inner function so you could, say, DisplayAs(|f| { if second != 0 { write!(f, "({}, {})", second >> 4, second & 0xF)?; } Ok(()) })?

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.