0

What is the canonical method of generating a string of N spaces in Go, similar to ' ' * n in Python?

I am currently building it myself as follows.

func spaces(n int) string {
    var sb strings.Builder
    for i := 0; i < n; i++ {
        sb.WriteString(" ")
    }
    return sb.String()
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Mark Harrison
  • 297,451
  • 125
  • 333
  • 465

1 Answers1

6

There's a strings.Repeat function in the standard library, so strings.Repeat(" ", n) would do. The implementation uses a strings.Builder like yours, except:

  1. It calls Grow on the builder ahead of time to guarantee only one allocation, instead of possibly reallocating several times in the middle.

  2. It progressively doubles the content of the builder instead of calling WriteString n times. Presumably they do that because it's more efficient.

For reasonable numbers of spaces, none of that probably makes any difference... but anyway, there's a stdlib function that expresses what you mean (really it's the direct equivalent of Python's str * int), so you might as well use it.

hobbs
  • 223,387
  • 19
  • 210
  • 288