Description
Proposal Details
Note
The current version of this proposal is here.
The signature in that version of the proposal is func Repeat[T any](count int, xs ...T) []T
.
I propose a small, trivial addition to the slices package.
// Repeat returns a new slice containing count copies of x.
func Repeat[T any](x T, count int) []T {
if count < 0 {
panic("count must be non-negative")
}
xs := make([]T, count)
for i := 0; i < count; i++ {
xs[i] = x
}
return xs
}
There's prior, related art in other languages with list-like types, including the following. (The Python and JavaScript examples were provided by @Jorropo and @earthboundkid; see below.) Not all of the below are identical in their behaviour, but they're thematically similar.
- Elixir, with List.duplicate/2.
- Haskell, with replicate in the Prelude.
- JavaScript, with Array.prototype.fill.
- Python, with
*
for sequences. - Ruby, with Array.new.
- Rust, with std::vec::Vec.repeat.
- Scala, with Array.fill.
I've personally found it a useful helper to have—particularly when combined with Concat, which looks like it'll make its way into Go 1.22.
I appreciate that slices oughtn't become a dumping ground for everyone's ideas about what's useful, but this feels like a natural addition to me.
I'm happy to contribute a pull request with tests if this is considered a good idea.