本文为译文 Variadic Functions
一般函数的参数个数都是固定的,可变函数即参数可变。
一般只有函数的最后一个参数是可变的。
func hello(a int, b ...int) {
}
hello(1, 2) //passing one argument "2" to b
hello(5, 6, 7, 8, 9) //passing arguments "6, 7, 8 and 9" to b
hello(1) //it is also possible to pass zero arguments for b.
- 可变参数变量一定要放到最后一个参数。
- go里面会把可变参数转换为一个slice类型。
传递一个slice参数给可变参函数
package main
import (
"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...)
}
如果参数是slice...传递给可变参数,那么就不会新创建一个slice了。
test
package main
import (
"fmt"
)
func change(s ...string) {
s[0] = "Go"
}
func main() {
welcome := []string{"hello", "world"}
change(welcome...)
fmt.Println(welcome) //Go world
}
正如上文说,如果使用 ...传递slice,不会创建新的slice。因此change函数其实拿到的参数就是welcome
package main
import (
"fmt"
)
func change(s ...string) {
s = append(s, "playground")
s[0] = "Go"
fmt.Println(s) //[Go world playground]
}
func main() {
welcome := []string{"hello", "world"}
change(welcome...)
fmt.Println(welcome) //[hello world]
}