golang不定长传参
2019-12-06 18:36
1196 查看
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 mysql查询返回不定字段
- GoLang中如何使用多参数属性传参
- function 函数传参,不定参,return返回值
- 了解golang的不定参数(... parameters),这一篇就够了
- golang实现ringbuffer(不定长)
- Golang的不定参数
- golang不定参数
- 返回值与不定参函数的传参
- javascript中arguments的应用——不定项传参求和
- Golang的不定参数
- Go_17:GoLang中如何使用多参数属性传参
- Golang 不定参数
- golang连接orcale
- 读取数量不定的输入数据
- VS Code的golang开发配置 之 代码提示
- 微信朋友圈转疯了(golang写小爬虫抓取朋友圈文章)
- Golang学习(8)——io 包
- golang 等价二叉树
- js中常用framesetiframe页面跳转传参方法实例大全
- Golang学习(13)——unicode包