LoginSignup
0
0

More than 3 years have passed since last update.

可変長引数構文(Go の関数の引数定義)

Last updated at Posted at 2019-08-04

こんにちは。
Go の関数の引数定義で、可変長引数構文を試してみました。

  • 参考にしたのは、"Passing arguments to ... parameters" (The Go Programming Language Specification) です。
  • 0個、1個、複数個を与えて試しました(T{} も与えてみました)。
$ go run sum2.go 
1
1
3
3
sum2.go
package main

import (
    "fmt"
)

type B struct {
    b  int
}

func sum2(a int, bs ...B) int {
    var b B
    if len(bs) > 0 {
        b = bs[0]
    }
    return a + b.b
}

func main() {
    fmt.Println(sum2(1)) // ==> 1
    fmt.Println(sum2(1, B{})) // ==> 1
    fmt.Println(sum2(1, B{2})) // ==> 3
    fmt.Println(sum2(1, B{2}, B{5})) // ==> 3
}
0
0
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
0
0