douzhiba6873 2018-12-17 02:13
浏览 80
已采纳

如何创建5个值都相同的数组/切片

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.

  • 写回答

2条回答 默认 最新

  • dongmei6426 2018-12-17 02:16
    关注

    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]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化