golang不定长传参
发表于:2024-11-24 作者:热门IT资讯网编辑
编辑最后更新 2024年11月24日,golang不定长传参,三个点... 可以很灵活的传入多个参数,给两个例子,一看就明白了1、int类型不定长传参package mainimport "fmt"func main() { fmt
golang不定长传参,三个点... 可以很灵活的传入多个参数,给两个例子,一看就明白了
1、int类型不定长传参
package mainimport "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 mainimport "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的顺序号和值0map[Italy:Rome]1map[Japan:Tokyo]2map[china:beijing]map[Italy:Rome Japan:Tokyo china:beijing]