Created
February 5, 2015 17:33
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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...) | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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