Home
Go
strings.Repeat Method
This page was last reviewed on 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 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.
This page was last updated on Sep 15, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.