How to fill a slice with values in Go
Created
Modified
Using for Loop
Using a for loop is the simplest solution. Fill the slice with the value 8 by looping through each element and setting the value.
package main
import "fmt"
func main() {
slice := make([]int64, 10, 10)
for i := 0; i < len(slice); i++ {
slice[i] = 8
}
fmt.Println(slice)
}
[8 8 8 8 8 8 8 8 8 8]
Using for range
For example,
package main
import "fmt"
func main() {
slice := make([]int64, 10, 10)
for i := range slice {
slice[i] = 8
}
fmt.Println(slice)
}
[8 8 8 8 8 8 8 8 8 8]
Using the copy trick
Example of using the copy trick to fill an array/slice with a multi-element pattern.
package main
import "fmt"
func main() {
// the pattern
pattern := []int64{8, 9, 10}
slice := make([]int64, 10, 10)
copy(slice, pattern)
for i := len(pattern); i < len(slice); i *= 2 {
copy(slice[i:], slice[:i])
}
fmt.Println(slice)
}
[8 9 10 8 9 10 8 9 10 8]
Using append Function
The resulting value of append is a slice containing all the elements of the original slice plus the provided values.
package main
import "fmt"
func main() {
slice := []int64{}
for i := 0; i < 10; i++ {
slice = append(slice, 8)
}
fmt.Println(slice)
}
[8 8 8 8 8 8 8 8 8 8]