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.
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...
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.
strings.Replace
, handle negative arguments in a special way.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.