I want to use println!
and the powerful formatting tools of format!
to print a character a specific number of times. Of course this is possible wit
If you want a cleaner way to repeat any Display
able item without creating an intermediate allocation, you can create a wrapper struct and write a custom Display
implementation that performs the repetition:
use std::fmt::{self, Display};
#[derive(Clone, Copy)]
struct DisplayRepeat(usize, T);
impl Display for DisplayRepeat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for _ in 0..self.0 {
self.1.fmt(f)?;
}
Ok(())
}
}
fn repeat(times: usize, item: T) -> DisplayRepeat {
DisplayRepeat(times, item)
}
fn main() {
println!("Here is love for you: {}", repeat(10, '♥'));
}