Skip to content

Instantly share code, notes, and snippets.

@giwa
Created February 5, 2015 17:33
Show Gist options
  • Save giwa/9552aa8db5f1d6d06d36 to your computer and use it in GitHub Desktop.
Save giwa/9552aa8db5f1d6d06d36 to your computer and use it in GitHub Desktop.
Go by Example: Variadic Functions ref: http://qiita.com/giwa@github/items/49b122c2f9397b6d9a23
package main
import "fmt"
// この関数は任意の数のintを引数として受け入れます。
func sum(nums ...int) {
fmt.Print(nums, " ")
total := 0
for _, num := range nums {
total += num
}
fmt.Println(total)
}
func main() {
// Variadic functionは個別の引数で通常はよばれます。
sum(1, 2)
sum(1, 2, 3)
// 複数の引数がsliceの中にある場合、func(slice...)をこのように使い、それらをvariadic funtionに与えることができます。
nums := []int{1, 2, 3, 4}
sum(nums...)
}
$ go run variadic-functions.go
[1 2] 3
[1 2 3] 6
[1 2 3 4] 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment