简体   繁体   中英

Rust: Formatting a formatted string

To print a string centered by 15 dashes, i'd do the following:

println!("{:-^15}", "Hi :D");

But what if i wanted to control the number of dashes that are put before and after my string? I tried the following:

let margin: usize = 15;
println!("{:-^{margin}}", "Hi :(");

And other variations, but all of them don't compile. What should i do?

You almost had the syntax of formatting parameters . Here are a few ways to use them:

println!("{:-^1$}", "Hi :D", 15);
let margin = 15;
println!("{:-^1$}", "Hi :D", margin);
println!("{:-^margin$}", "Hi :D");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM