首页 > 其他 > 详细

golang不定长传参

时间:2019-12-06 21:26:36      阅读:98      评论:0      收藏:0      [点我收藏+]
golang不定长传参,三个点... 可以很灵活的传入多个参数,给两个例子,一看就明白了

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不定长传参

原文:https://blog.51cto.com/daixuan/2456761

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!