0
0

More than 3 years have passed since last update.

【Golang】可変長引数

Posted at

【Golang】可変長引数

Golangの基礎学習〜Webアプリケーション作成までの学習を終えたので、復習を兼ねてまとめていく。 基礎〜応用まで。

package main
//可変長引数
//複数の引数を渡す際、決まった個数でない場合。

import "fmt"

//可変長引数   ...int
func foo(params ...int) {
    //引数の長さ表示
    fmt.Println(len(params), params)
    //引数の長さ分繰り返す 
    //_にはインデックスが入る。
    for _, param := range params {
        fmt.Println(param)
    }
}

func main() {
    foo()
    //>>0 []
    foo(10, 20)
    //>>2 [10 20]
    //>>10
    //>>20
    foo(10, 20, 30)
    //>>3 [10 20 30]
    //>>10
    //>>20
    //>>30

    //スライス作成
    s := []int{1, 2, 3}

    //表示
    fmt.Println(s)
    //>>[1 2 3]

    //スライスを引数に展開して渡す
    //foo(s)ではエラーになる
    foo(s...)
    //>>3 [1 2 3]
    //1
    //2
    //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