go语言 – 将切片传递给变参函数

让我们将切片作为变参参数值,传递给变参函数,看看会怎么样?

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)
}

上面的程序会报编译错误:

cannot use nums (type []int) as type int in argument to find

不能直接把切片作为变参参数值,传入变参函数。

但我们可以使用一种语法糖,可以将一个切片传递给变参函数。必须在切片后面加上省略号,这样切片就可以传递给函数。

在上面的程序中,把find(89, nums)替换为find(89, nums…),程序将通过编译并打印以下输出。

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

下面是完整的程序。

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...)
}

变参函数中修改传入的切片

变参函数中修改传入的切片,将修改引用的数组中的值。

package main

import (  
    "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)
}

输出:

[Go world]


浙ICP备17015664号-1 浙公网安备 33011002012336号 联系我们 网站地图  
@2019 qikegu.com 版权所有,禁止转载