Go语言中,经常可以看到一些参数定义时带
...
,例如
// Println formats using the default formats for its operands and writes to standard output.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Println(a ...any) (n int, err error) {
return Fprintln(os.Stdout, a...)
}
这里总结下...
的用法
1. 用于省略定义数组时声明数组长度
a := [3]int{1, 2} // 未初始化元素值为 0。
b := [...]int{1, 2, 3, 4} // 通过初始化值确定数组长度。
2. 表示拆开切片
切片并不是数组或数组指针。它通过内部指针和相关属性引用数组片段,以实现变长方案
var a = []int{1, 2, 3}
fmt.Printf("slice a : %v\n", a)
var b = []int{4, 5, 6}
fmt.Printf("slice b : %v\n", b)
c := append(a, b...)
fmt.Printf("slice c : %v\n", c)
====
输出结果:
slice a : [1 2 3]
slice b : [4 5 6]
slice c : [1 2 3 4 5 6]
这里的…
表示拆开,
a = append(a, b…)等价于a = append(a, b[0], b[1], b[2])
3. 表示可以接收可变参数
当有多个参数时可变参数需要放在最后面
func main(){
output("a","b","c")
}
func output(name ...string){
fmt.Println(name)
}
如果没有...
, 函数报错