golang不定長傳參,三個點... 能夠很靈活的傳入多個參數,給兩個例子,一看就明白了golang
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
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]