Lukas Kalbertodt February 2016

Printing a character a variable number of times with println

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 with a loop, like so:

fn give_love(count: usize) {
    print!("Here is love for you: ");
    for i in 0..count {
        print!("♥");
    }
    println!("");
}

But I neither want to write the loop nor the three prints. How to do this shorter/better?

Answers


Lukas Kalbertodt February 2016

Solution to your code

fn give_love(count: usize) {
    println!("Here is love for you: {:♥<1$}", "", count);
}

Explanation

You can (mis-)use the fill feature that allows to fill a printed value with some character of your choice. The grammar for this feature alone looks like:

'{' ':' <fill> <align> <width> '}'

Where width is either a constant number or a reference to an argument of type <argument_index> '$'. So 3 would mean a width of constant 3 and 1$ would mean a width of the value of the 1st argument of println!.


However: here we are kind of "misusing" this feature and we mustn't forget that we are only specifying the "fill" for some other printable thing, which is passed by argument to println. This can be an empty string though.

println!("love: {:♥<3}", "");     // love: ♥♥♥
println!("love: {:♥<1$}", "", 5); // love: ♥♥♥♥♥

Here are some examples where we don't pass an empty string:

println!("love: {:♥<5}", "#");    // love: #♥♥♥♥
println!("love: {:♥>5}", "#");    // love: ♥♥♥♥#
println!("love: {:♥^5}", "#");    // love: ♥♥#♥♥

Post Status

Asked in February 2016
Viewed 2,453 times
Voted 11
Answered 1 times

Search




Leave an answer