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.
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.