Idiomatic way to Concat Leading Zeros in Go

Mil*_*orn 1 idiomatic go leading-zero

I came up with a way to pad leading zeros into a Go string. I'm not sure if this is the way you do this in Go. Is there a proper way to do this in Go? This is what I came up with and can be found inside the second if block. I tried Google to see if it had something built in without luck.

func integerToStringOfFixedWidth(n int, w int) string {
  s := strconv.Itoa(n)
  l := len(s)

  if l < w {
    for i := l; i < w; i++ {
      s = "0" + s
    }
    return s
  }
  if l > w {
    return s[l-w:]
  }
  return s
}
Run Code Online (Sandbox Code Playgroud)

For n = 1234 and w = 5, the output should be integerToStringOfFixedWidth(n, w) = "01234".

Ken*_*ant 5

You can use Sprintf/Printf for that (Use Sprintf with the same format to print to a string):

package main

import (
    "fmt"
)

func main() {
    // For fixed width
    fmt.Printf("%05d", 4)

    // Or if you need variable widths:
    fmt.Printf("%0*d", 5, 1234)
}
Run Code Online (Sandbox Code Playgroud)

https://golang.org/pkg/fmt/

See other flags in the docs - pad with leading zeros rather than spaces

https://play.golang.org/p/0EM4aE2Hk6H