Problem
In go programming language, how to create an array of length 5, with all elements has same value, eg, 42.
Preference order
readability, conciseness, performance.
For example,
package main
import (
"fmt"
)
func main() {
s := make([]int, 5)
for i := range s {
s[i] = 42
}
fmt.Println(len(s), s)
}
Playground: https://play.golang.org/p/GjTXruMsJ5h
Output:
5 [42 42 42 42 42]
Some benchmarks:
package main
import (
"fmt"
"testing"
)
func BenchmarkStack(b *testing.B) {
for N := 0; N < b.N; N++ {
s := make([]int, 5)
for i := range s {
s[i] = 42
}
}
}
func BenchmarkHeap(b *testing.B) {
var s []int
for N := 0; N < b.N; N++ {
s = make([]int, 5)
for i := range s {
s[i] = 42
}
}
}
func BenchmarkHygull(b *testing.B) {
for N := 0; N < b.N; N++ {
var s []int
for i := 0; i < 5; i++ {
s = append(s, 42)
}
}
}
Output:
$ go test slice42_test.go -bench=. -benchmem
BenchmarkStack-8 1000000000 2.05 ns/op 0 B/op 0 allocs/op
BenchmarkHeap-8 100000000 26.9 ns/op 48 B/op 1 allocs/op
BenchmarkHygull-8 10000000 123 ns/op 120 B/op 4 allocs/op
$
BenchmarkHygull
demonstrates how inefficient @hygull's solution is.
A "one-liner":
package main
import (
"fmt"
)
func newInts(n, v int) []int {
s := make([]int, n)
for i := range s {
s[i] = v
}
return s
}
func main() {
s := newInts(5, 42)
fmt.Println(len(s), s)
}
Playground: https://play.golang.org/p/t8J-AjYQ72l
Output:
5 [42 42 42 42 42]
The best way to do will be to use slice for that as it can grow dynamically.
Currently, you are looking only for 5 values so using arrays also is not a problem but what if you are looking for dynamic size (i.e. if you specify size of array in run time, there may be a chance of either going beyond the range or not using all the allocated spaces).
So I think the following code is sufficient to understand that.
package main
import "fmt"
func main() {
var s []int
value := 42 // It can be changed to other values
for i := 0; i < 5; i++ {
s = append(s, value)
}
fmt.Println(s); // [42 42 42 42 42]
}