Home
Go
strings.Repeat Method
Updated Sep 15, 2024
Dot Net Perls
Repeat. With the Repeat func we can repeat a string. The first argument is the string we want to repeat, and the second is the count of repetitions.
This method can be useful when we need to do benchmarks on a large string. We could just call strings.Repeat instead of building up a string directly.
strings.Builder
Example. For creating repeating text, using Repeat() with a string literal is a good solution. Here we repeat a string literal with the letters "abc" 3 times.
package main import ( "fmt" "strings" ) func main() { // Create a new string based on a repetition. result := strings.Repeat("abc...", 3) fmt.Println(result) }
abc...abc...abc...
Repeat panic. The second argument to strings.Repeat() is the count of repetitions we want in the resulting string. Having a negative number makes no sense, so this leads to a panic.
Info Some methods in Go, like strings.Replace, handle negative arguments in a special way.
strings.Replace
package main import ( "strings" ) func main() { value := "a" // Cannot repeat negative amount. strings.Repeat(value, -1) }
panic: strings: negative Repeat count goroutine 1 [running]: ... exit status 2
Though it is rarely needed, strings.Repeat can be useful in certain programs where we want large strings to test our programs. It can avoid the need writing a messy loop where we concat repeatedly.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Sep 15, 2024 (new).
Home
Changes
© 2007-2025 Sam Allen