Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
53
Help us understand the problem. What is going on with this article?
@hnakamur

Goで可変引数の関数にスライスを展開して渡す

More than 5 years have passed since last update.

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
で試せます。

53
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
hnakamur
sakura_internet
さくらレンタルサーバ、さくらのVPS、 さくらのクラウド、さくらの専用サーバなどのインターネットサービス・ITプラットフォームを提供しています。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
53
Help us understand the problem. What is going on with this article?