I need a (non-loopy) way to create a slice of ints
with n
repeated copies of an element (say 10
).
Something equivalent of strings.Repeat("a", n)
but for []int
.
Asked
Active
Viewed 3,452 times
-3

Jonathan Hall
- 75,165
- 16
- 143
- 189

VaidAbhishek
- 5,895
- 7
- 43
- 59
1 Answers
1
You could just capture it in a simple function:
func repeatedSlice(value, n int) []int {
arr := make([]int, n)
for i := 0; i < n; i++ {
arr[i] = value
}
return arr
}
Here is a working example.

squiguy
- 32,370
- 6
- 56
- 63