95
55

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で可変引数の関数にスライスを展開して渡す

Posted at

http://golang.org/ref/spec#Passing_arguments_to_..._parameters
で説明されています。

スライスの変数の後に...をつけて呼び出せば、Goで可変引数の関数にスライスを展開して渡すことができます。

試しに変数を用意せずに配列のリテラルの後に...をつけて見ましたが、こちらでも動作しました。

package main

import "fmt"

func main() {
	// normal variadic function call
	greeting("Hello", "世界", "日本")

	// you can pass an array with following '...'
	// http://golang.org/ref/spec#Passing_arguments_to_..._parameters
	names := []string{"世界", "日本"}
	greeting("Hi", names...)

	// actually you can pass an array literal following '...'
	greeting("Yay", []string{"世界", "日本"}...)
}

func greeting(prefix string, who ...string) {
	fmt.Printf("%s", prefix)
	for _, name := range who {
		fmt.Printf(" %s", name)
	}
	fmt.Printf("\n")
}

上のプログラムは
http://play.golang.org/p/9Yhowss0JM
で試せます。

95
55
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
95
55

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?