Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rust, how to use variable in format! macro?

Tags:

format

rust

I have a very simple program:

fn main() {
    let y = format!("{:0>3}", 11);
    println!("{}", y);
}

The output is the string 011. The problem is that the width specifier 3 in {:0>3} is coming from a variable like this:

fn main() {
    let x = 3usize;
    let y = format!("{:0>3}", 11);
    println!("{}", y);
}

How can I use variable x to replace 3 in {:0>3}?

like image 750
Just a learner Avatar asked Jun 18 '21 19:06

Just a learner


1 Answers

fn main() {
    let x = 3;
    let y = format!("{:0>width$}", 11, width=x);
    println!("{}", y);
}

As it may be hard to remember the whole formatting syntax, it's a good idea to get used to find the reference.

like image 73
Denys Séguret Avatar answered Sep 20 '22 05:09

Denys Séguret