How to create an array/slice of 5 value, all of same value

后端 未结 2 946
离开以前
离开以前 2021-01-07 14:49

Problem

In go programming language, how to create an array of length 5, with all elements has same value, eg, 42.

Preference order

2条回答
  •  天命终不由人
    2021-01-07 15:34

    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]
    

提交回复
热议问题