How to use variable in format string?

println!("{0: <20    }  {0}  " , "zzzzzzzz"  ) ;
//  __________ ^^ ___________

works!
But, the same thing with variable does not.

let my_len:i8=20; 
for i in 0..v.len()  {
   println!("{0: <my_len    }{0} " , v[i]    ) ;
//  _____________ ^^^^^^ ___________

error: unknown format trait my_len

I am trying to get simple table-like output without external crate.

Use {0:<1$}. You can embed nth parameter inside the formatting parametre using n$ in some context.
See https://doc.rust-lang.org/stable/std/fmt/index.html#width.

fn main() {
    let my_len: usize = 20;
    println!("{0:<20    }  {0}  ", "zzzzzzzz");
    println!("{0:<1$}  {0}  ", "zzzzzzzz", my_len);
    let v = vec![1, 22, 333, 4444, 55555];
    for elem in v {
        println!("{0:<1$}{0} ", elem, my_len);
    }
}
1 Like

You don't need to make it positional, the dollar sign is the key.

fn main() {
    let y = 17;
    let w = 40;
    println!("x{y:<w$}x")
}
4 Likes

I read that chapter and saw that $ sign, but I gone through: "$-sign is so unclear, it seems too deep level, only for experts".

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.