Why does the rust string not have a method for adding leading zeros like `zfill`?

Normally you can add leading zeros like this

assert_eq!(format!("{:04}", 5), "0005".to_string());

but I had to add leading zeros based on a variable

let alignment = 4;
format!(); // How ?

This is afaik currently not possible and I ended up with this

trait StringExt {
    fn zfill(&self, value: usize) -> String;
}

impl StringExt for String {
    fn zfill(&self, value: usize) -> String {
        let mut result = self.clone();

        while result.len() < value {
            result = format!("0{}", result);
        }

        result
    }
}

assert_eq!("5".to_string().zfill(alignment), "0005".to_string());

Is there really no built in method to do this?

This is possible to do with the formatting language, although the syntax is weird: where you are using the value 4 ({:04}), you need to put a parameter followed by $, where a parameter is what you would write before the colon to specify which argument you refer to (they can be positional, e.g., 0 for the first argument, 1 for the second, etc.; or they can be named, which I recommend using for greater readability).

Example:

let alignment = 4;
format!("{:0fill$}", 5, fill = alignment)
9 Likes