dongjun111111 / blog

BLOG
36 stars 5 forks source link

Golang可变参数函数 #37

Open dongjun111111 opened 8 years ago

dongjun111111 commented 8 years ago

Golang 可变参数函数

可变参数函数。可以用任意数量的参数调用。例如,fmt.Println 是一个常见的变参函数。

这个函数使用任意数目的 int 作为参数。

变参函数使用常规的调用方式,除了参数比较特殊。

如果你的 slice 已经有了多个值,想把它们作为变参使用,你要这样调用 func(slice...)。

package main

import (
    "fmt"
)
func sum(nums ...int){
    fmt.Println(nums," ")
    total := 0
    for _,num := range nums{
        total +=num
    }
    fmt.Println(total)
}
func main(){
    sum(4,5,6,7,8,5)
    nums := []int{3,6,5,44,5,3}
    sum(nums...)
}
output==>
[4 5 6 7 8 5]  
35
[3 6 5 44 5 3]  
66

参考

www.yushuangqi.com