例:求若干个整数累加,类型int前置三个点(...)操作符表示参数是若干个整数
package main import ( "fmt" ) func main() { fmt.Println(sum(2, 3)) fmt.Println(sum(2, 3, 4)) } func sum(nums ...int) int { result := 0 for _, num := range nums { result = result + num } return result }
对于上面的sum函数,可以传入切片slice形式,但是要用切片slice后置三个点(...)表示将切片打散开,如:
package main import ( "fmt" ) func main() { numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} fmt.Println(sum(numbers...)) } func sum(nums ...int) int { result := 0 for _, num := range nums { result = result + num } return result }
参考:https://www.cnblogs.com/apocelipes/p/9861315.html