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