rust - Printing a character a variable number of times with println -
i want use println! , powerful formatting tools of format! print character specific number of times. of course possible loop, so:
fn give_love(count: usize) { print!("here love you: "); in 0..count { print!("♥"); } println!(""); } but neither want write loop nor 3 prints. how shorter/better?
solution code
fn give_love(count: usize) { println!("here love you: {:♥<1$}", "", count); } explanation
you can (mis-)use fill feature allows fill printed value character of choice. grammar feature alone looks like:
'{' ':' <fill> <align> <width> '}' where width either constant number or reference argument of type <argument_index> '$'. 3 mean width of constant 3 , 1$ mean width of value of 1st argument of println!.
however: here kind of "misusing" feature , mustn't forget specifying "fill" other printable thing, passed argument println. can empty string though.
println!("love: {:♥<3}", ""); // love: ♥♥♥ println!("love: {:♥<1$}", "", 5); // love: ♥♥♥♥♥ here examples don't pass empty string:
println!("love: {:♥<5}", "#"); // love: #♥♥♥♥ println!("love: {:♥>5}", "#"); // love: ♥♥♥♥# println!("love: {:♥^5}", "#"); // love: ♥♥#♥♥
Comments
Post a Comment