packagemainimport"fmt"funcfind(num int, nums ...int) { fmt.Printf("type of nums is %T\n", nums) found :=falsefor i, v :=range nums {if v == num { fmt.Println(num, "fount at index", i, "in", nums) found =true } }if!found { fmt.Println(num, "not found in ", nums) } fmt.Println()}funcmain() {find(89, 89, 90, 95)find(45, 56, 67, 45, 90, 109)find(78, 38, 56, 98)find(87)}
Go Playground在线运行 该程序中,func find(num int, nums ...int)的参数nums即为可变参数。在函数find内部,我们打印出了nums参数的类型,打印结果为[]int,可以看出在函数内部,可变参数的类型是切片,这里nums类型是整型切片。
type of nums is []int
89 fount at index 0 in [89 90 95]
type of nums is []int
45 fount at index 2 in [56 67 45 90 109]
type of nums is []int
78 not found in [38 56 98]
type of nums is []int
87 not found in []
packagemainimport"fmt"funcfind(num int, nums ...int) { fmt.Printf("type of nums is %T\n", nums) found :=falsefor i, v :=range nums {if v == num { fmt.Println(num, "fount at index", i, "in", nums) found =true } }if!found { fmt.Println(num, "not found in ", nums) } fmt.Println()}funcmain() { nums := []int{89, 90, 95}find(89, nums)}
packagemainimport"fmt"funcfind(num int, nums ...int) { fmt.Printf("type of nums is %T\n", nums) found :=falsefor i, v :=range nums {if v == num { fmt.Println(num, "fount at index", i, "in", nums) found =true } }if!found { fmt.Println(num, "not found in ", nums) } fmt.Println()}funcmain() { nums := []int{89, 90, 95}find(89, nums...)}