Go Reference ยท strings and strconv
Go strings.Repeat() function
Reference for Go strings.Repeat: build a string from a piece repeated count times, for separators, indentation and padding, and why a negative count panics.
strings.Repeat(s, count) returns a new string made of s repeated count times. It is the standard way to draw separator lines, build indentation, or pad text.
Unlike languages where you multiply a string by a number, Go needs this function. It computes the final size up front and fills it efficiently, so it is faster than looping with +=.
line := strings.Repeat("=", 20)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Repeat(s string, count int) string
| Name | Description |
|---|---|
s |
The string to repeat. |
count |
How many copies. 0 gives the empty string. |
Returns: the repeated string.
Errors and panics: Repeat panics if count is negative, or if len(s) * count overflows the maximum string size. The panic message for a negative count is strings: negative Repeat count.
Usage notes
- Validate untrusted counts. If
countcomes from user input, clamp it, because a large count can allocate a huge string and exhaust memory. - Padding: for plain alignment prefer
fmt.Printf("%-10s", s)or%08d(see width and flags);Repeatis for dynamic or non-space padding characters. - Length counts runes, not bytes.
len(s)is bytes; useutf8.RuneCountInStringfor display width, as the example does with[]rune. - Repeating a byte or rune:
strings.Repeat(string(r), n)works;bytes.Repeatproduces a[]byte. - Repeating with separators:
strings.TrimSuffix(strings.Repeat("?,", 3), ",")gives?,?,?, handy for SQL placeholders. - Immutable: the result is a fresh string; the argument is untouched.
- Complexity: O(len(s) * count) time and memory, using a doubling copy strategy.