rust

Format specifier for truncating string-like types


Is there a format specifier that will truncate a string-like type? I have a type which is not a String, but does implement Display. I want to limit it to be 7 characters long though, and the only way I know how to do that is to convert it to string first.

let sha1 = format!("{}", branch.commit_id);
let formatted = format!("{} ({})\n", branch.name, &sha1[0..7]));

Is there some format specifier that will let me do that in one step? Something like:

let formatted = format!("{} ({<something 7>})\n", branch.name, branch.commit_id);

Unfortunately, because it is not a string, I can't just do &branch.commit_id[0..7], which is why I'm hoping there is a format specifier syntax for that.


Solution

  • I stumbled across it a few days later. There is a format specifier which does this.

    println!("Hello {:.5}", "world <-- only the the first 5 characters will be printed");
    

    Edit: As Stargateur pointed out in the comments, this does not work in the general case. It happened to work in mine because I was using a git2::Oid, whose Display implementation happens to convert itself to str before calling .fmt(f) on itself (src).