LoginSignup
1
3

More than 5 years have passed since last update.

[Go]可変長のsliceを展開、受け取る時の記述方法

Posted at

three dots

可変長引数を表す...という記法。展開して渡す側、受け取り側で記述方法が混乱したので書いておく

sample.go
package main

import (
    "fmt"
)

func main() {
    holiDays("JUN")
    holiDays("MAY", 3, 4, 5)

    days := []int{1, 8}
    holiDays("JAN", days...)

}

func holiDays(month string, days ...int) {
    fmt.Println(month)
    fmt.Println(days)
}

上記のようなコードの場合...

  • 引数として受け取る場合はdays ...intと型名の手前にthree dotsで記述する
  • sliceを展開して渡す場合はdays...と記述する
1
3
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
3