Golang中 "..." 的几种用法

在Go中,经常可以见到 … 能概括一下 … 的使用场景吗

  1. 用在函数参数中

    若函数的最后一个参数是…T类型,这个参数可传入任意个T类型的参数,在函数中…T的类型为[]T.

    在这个例子函数中,你可以这样使用这个函数Sum(1,2,3)orSum().

    func Sum(nums ...int) int {
        res := 0
        for _, n := range nums {
            res += n
        }
        return res
    }
    
  1. 用在解序列

    可以传入一个slice,然后用…解开它,注意在这里没有新的slice被创造。在这个例子函数中,我们把slice传入Sum函数

    primes := []int{2, 3, 5, 7}
    fmt.Println(Sum(primes...)) // 17
    

    在append函数的注释中,同样可以看到...

    //It is therefore necessary to store the
    // result of append, often in the variable holding the slice itself:
    //   slice = append(slice, elem1, elem2)
    //   slice = append(slice, anotherSlice...)
    
  1. 用在数组中

    在一个数组的声明中,...相当于指定一个和元素个数相同的长度

    stooges := [...]string{"Moe", "Larry", "Curly"} // len(stooges) == 3
    
  1. 用在Go命令中

    在go命令中,...可以作为一个列出所有包名的通配符

    这个命令列出当前和子目录中所有的包

    go test ./...
    

参考:
three-dots-ellipsis

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。