# [译] part 12: goalng 变参函数

https://juejin.im/post/5cb83e8de51d456e6154b423

## 示例

append函数可以增加任意数量的参数给切片。变参函数就是用到了切片的这个原理。

func append(slice []Type, elems ...Type) []Type

package mainimport (      "fmt")func find(num int, nums ...int) {      fmt.Printf("type of nums is %T\n", nums)    found := false    for i, v := range nums {        if v == num {            fmt.Println(num, "found at index", i, "in", nums)            found = true        }    }    if !found {        fmt.Println(num, "not found in ", nums)    }    fmt.Printf("\n")}func main() {      find(89, 89, 90, 95)    find(45, 56, 67, 45, 90, 109)    find(78, 38, 56, 98)    find(87)}

Run in playground

type of nums is []int  89 found at index 0 in [89 90 95]type of nums is []int  45 found 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  []

## 使用切片作为变参函数的参数

package mainimport (      "fmt")func find(num int, nums ...int) {      fmt.Printf("type of nums is %T\n", nums)    found := false    for i, v := range nums {        if v == num {            fmt.Println(num, "found at index", i, "in", nums)            found = true        }    }    if !found {        fmt.Println(num, "not found in ", nums)    }    fmt.Printf("\n")}func main() {      nums := []int{89, 90, 95}    find(89, nums)}

Run in playground

func find(num int, nums ...int)

find(89, []int{nums})

type of nums is []int  89 found at index 0 in [89 90 95]

package mainimport (      "fmt")func find(num int, nums ...int) {      fmt.Printf("type of nums is %T\n", nums)    found := false    for i, v := range nums {        if v == num {            fmt.Println(num, "found at index", i, "in", nums)            found = true        }    }    if !found {        fmt.Println(num, "not found in ", nums)    }    fmt.Printf("\n")}func main() {      nums := []int{89, 90, 95}    find(89, nums...)}

Run inplayground

## 注意事项

package mainimport (      "fmt")func change(s ...string) {      s[0] = "Go"}func main() {      welcome := []string{"hello", "world"}    change(welcome...)    fmt.Println(welcome)}

Run in playground

change函数内部，切片的第一个元素更改为 Go。因此该程序输出

[Go world]

package mainimport (      "fmt")func change(s ...string) {      s[0] = "Go"    s = append(s, "playground")    fmt.Println(s)}func main() {      welcome := []string{"hello", "world"}    change(welcome...)    fmt.Println(welcome)}

Run in playground