2
0

More than 3 years have passed since last update.

眺めて覚えるGo言語 その6 可変引数

Posted at

Go言語で可変引数を使う。

では、眺める例題

main.go
ackage main
import(
    "fmt"
    "reflect"
)
func f(args ...interface{}){
    for i,arg:=range args{
        fmt.Println(i,reflect.TypeOf(arg),arg)
    }
}
func sum(a int,b int) int{
    return a+b
}
func main(){
    f(10.0/3,10,20,30,"Tokyo",sum,sum(5,10))
}

0 float64 3.3333333333333335
1 int 10
2 int 20
3 int 30
4 string Tokyo
5 func(int, int) int 0x4bb2a0
6 int 15
Process exiting with code: 0

注目すべき書き方

-args ...interface{}
可変引数
f(10.0/3,10,20,30,"Tokyo",sum,sum(5,10))

  • 10.0/3 実数を渡す
  • 10,20,30 整数を渡す
  • "Tokyo" 文字列を渡す
  • sumは、関数を渡す
  • sum(5,10)は、関数の答えを渡す

変数の取り出し方

f.go
func f(args ...interface{}){
    for i,arg:=range args{
        fmt.Println(arg)
    }
}

for range で取り出す

応用問題 fmt.Printlnに書き疲れたら

main.go
package main
import(
    "fmt"
)
func main(){
    for i:=0;i<10;i++{
        p(i,"hello world")
    }   
}
func p(a ...interface{}){
    fmt.Println(a...);
}

0 hello world
1 hello world
2 hello world
3 hello world
4 hello world
5 hello world
6 hello world
7 hello world
8 hello world
9 hello world
Process exiting with code: 0

「いいね」ボタン押してね! :relaxed:

2
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
2
0