Go函数接收可变参数

package main

import(
	"fmt"
	"reflect"
)

func receiveSlice(manyints ...int) { //该函数可接收多个int参数, 打包为[]int类型slice
	fmt.Println(reflect.TypeOf(manyints), len(manyints), cap(manyints))
	fmt.Printf("%#v \n",manyints)
}
func receiveFourInts(var1, var2, var3, var4 int){
	fmt.Printf("%#v%#v%#v%#v",var1, var2, var3, var4)
}

func main(){
	receiveSlice(1,2,3,4)
	receiveSlice(1,2,3,4,5,6,7,8)
	slice := []int{1,2,3,4}
	//receiveSlice(slice) //报错
	//receiveFourInts(slice...) //报错, var...用法只能用于接收参数为 ...type的函数
	receiveSlice(slice...) //正常
}

输出

[]int 4 4
[]int{1, 2, 3, 4} 
[]int 8 8
[]int{1, 2, 3, 4, 5, 6, 7, 8} 
[]int 4 4
[]int{1, 2, 3, 4} 

你可能感兴趣的:(Go,go,golang,可变参数,数组,切片)