代码点读机 / Go / ...

... Go · 符号

三个点:在函数参数中表示可变参数;在调用时把切片展开成多个参数。

怎么用

func f(a ...int) 定义可变参数;f(slice...) 展开切片

小例子

package main
import "fmt"

func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

func main() {
    fmt.Println(sum(1, 2, 3))
}

运行结果

输出 6

提醒:可变参数在函数内部被当成切片使用

官方文档:https://go.dev/ref/spec#Function_types

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Go全部词条