0
0

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.

可変長引数

Last updated at Posted at 2019-06-11
func hoge(param1, param2 int) {
	sum := param1 + param2
	fmt.Println(sum)
}

func main() {
	hoge(23, 30)
}

関数hogeは引数を2つしか受け付けないので、プログラムの途中で引数を増やしたい場合などに対応できない。
そういう時に備えて可変長引数を使う。

中身を展開して確認しながら見ていく。

func hoge(params ...int) {
	fmt.Println(len(params), params)
	for _, param := range params {
		fmt.Println(param)
	}
}
func main() {
	hoge(10, 20)
	// 2 [10 20]
	// 10
	// 20

	hoge(20, 30, 60)
	// 3 [20 30 60]
	// 20
	// 30
	// 60

	hoge()
	// 0 []

	s := []int{1, 2, 3}
	fmt.Println(s) //[1 2 3]

	hoge(s...)
	// 3 [1 2 3]
	// 1
	// 2
	// 3
}

func hoge(params ...int)のように...をつけることで可変長引数を使うことができる。

【参考】
現役シリコンバレーエンジニアが教えるGo入門(https://www.udemy.com/share/100BhMB0obeFpbTX4=/)

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?