golang不定长传参

golang不定长传参,三个点... 可以很灵活的传入多个参数,给两个例子,一看就明白了

创新互联公司2013年成立,是专业互联网技术服务公司,拥有项目网站设计制作、成都网站建设网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元振安做网站,已为上家服务,为振安各地企业和个人服务,联系电话:13518219792

1、int类型不定长传参

package main

import "fmt"

func main() {
    fmt.Println(Sum(1, 4, 6, 7, 8, 9, 100, 200))
}

func Sum(numbers ...int) int {
    result := 0
    for _, n := range numbers {
        result += n
    }
    return result
}
 go run test1.go 
335

2、map类型不定长传参

package main

import "fmt"

func main() {
    fmt.Println(SumMap(map[string]string{"Italy": "Rome"}, map[string]string{"Japan": "Tokyo"}, map[string]string{"china": "beijing"}))
}

func SumMap(countryCapitalMaps ...map[string]string) map[string]string {
    var result map[string]string
    result = make(map[string]string)
    //注意:这里需要先把多个map的顺序取出,否则会报错
    //cannot use k (type int) as type string in map index
    //cannot use v (type map[string]string) as type string in assignment
    for i, num := range countryCapitalMaps {
        fmt.Println(i)
        fmt.Println(num)
        for k, v := range num {
            result[k] = v
        }
    }
    return result
}
go run test2.go  //这里会打印map的顺序号和值
0
map[Italy:Rome]
1
map[Japan:Tokyo]
2
map[china:beijing]
map[Italy:Rome Japan:Tokyo china:beijing]

网站栏目:golang不定长传参
URL链接:http://scjbc.cn/article/pgspcg.html

其他资讯