1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go by Example: Variadic Functions

Posted at

(この記事は Go by Example: Variadic Functions を翻訳したものです。)

Variadic functions はどんな数の引数でも関数が呼ばれる事ができます。たとえば、fmt.Printlnはよくつかわれる Variadic functionです。

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

他の重要なGoの関数の特徴は、次に見るClosureです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?