Printing a character a variable number of times with println

后端 未结 2 1092
野的像风
野的像风 2021-01-11 22:28

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

2条回答
  •  执念已碎
    2021-01-11 23:32

    If you want a cleaner way to repeat any Displayable 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, '♥'));
    }
    

提交回复
热议问题