# Go语言可变参数函数，何时该使用省略号(...)

1、提出假想的需求 假如想要在一堆数据中找出最小的一个，该怎么做？

func MinimumInt(first int, others ...int) int { min := first for _, value := range others { if value < min { min = value } } return min}

func MinimumInt(others ...int) int {}

MinimumInt(10, 15, 32, 46, 2, 3) //1 var sliceInt = []int{10, 15, 32, 46, 2, 3} MinimumInt(sliceInt[0], sliceInt[1], sliceInt[2], sliceInt[3], sliceInt[4], sliceInt[5]) //2 MinimumInt(sliceInt[0], sliceInt[1:]...) //3

2、完善需求

func Minimum(first interface{}, rest ...interface{}) interface{} { min := first for _, value := range rest { switch value := value.(type) { case int: if value < min.(int) { min = value } case float64: if value < min.(float64) { min = value } case string: if value < min.(string) { min = value } } } return min}

Minimum(10, 15, 32, 46, 2, 3) //1 var sliceInt = []int{10, 15, 32, 46, 2, 3} Minimum(sliceInt[0], sliceInt[1], sliceInt[2], sliceInt[3], sliceInt[4], sliceInt[5]) //2 Minimum(sliceInt[0], sliceInt[1:]...) //3

# command-line-arguments./test.go:14: cannot use sliceInt[1:] (type []int) as type []interface {} in argument to Minimum

Minimum(sliceInt[0], sliceInt[1:])

MinimumInt(sliceInt[0], sliceInt[1:]) //不再使用省略号展开

# command-line-arguments./test.go:15: cannot use sliceInt[1:] (type []int) as type int in argument to MinimumInt

var i int = 10 var sliceInt = []int{10, 15, 32, 46, 2, 3} var sliceIntz [][]int = [][]int{[]int{1, 2, 3}, []int{4, 5, 6}, []int{7, 8, 9}} var inter_a interface{} = i //int var inter_b interface{} = sliceInt //[]int var inter_c interface{} = sliceIntz //[][]int

var inter_d []interface{} = sliceInt[:]

# command-line-arguments./test.go:27: cannot use sliceInt[:] (type []int) as type []interface {} in assignment

var inter_d []interface{} = []interface{}{sliceIntz[0], sliceIntz[1], sliceIntz[2]}

Minimum(sliceInt[0], sliceInt[1], sliceInt[2], sliceInt[3])

Minimum(sliceInt[0], sliceInt[1:])

func Minimum(first interface{}, rest ...interface{}) interface{} { min := first fmt.Printf("%T/t%T/n", rest, rest[0]) //打印类型信息 for _, value := range rest { switch value := value.(type) { case int: if value < min.(int) { min = value } case float64: if value < min.(float64) { min = value } case string: if value < min.(string) { min = value } } } return min}

fmt.Println(Minimum(sliceInt[0], sliceInt[1], sliceInt[2], sliceInt[3], sliceInt[4], sliceInt[5]))//结果为：//[]interface {} int//2

fmt.Println(Minimum(sliceInt[0], sliceInt[1:]))//结果为：//[]interface {} []int//10