Skip to content

Instantly share code, notes, and snippets.

@kwmt
Created October 9, 2013 03:30
Show Gist options
  • Save kwmt/6895772 to your computer and use it in GitHub Desktop.
Save kwmt/6895772 to your computer and use it in GitHub Desktop.
#golang リフレクションを使って、キャストする。
package main
import (
"fmt"
"reflect"
"strconv"
)
func main() {
var mode bool = true
var f interface{}
if mode {
f = strconv.FormatInt
} else {
f = strconv.FormatUint
}
fv := reflect.ValueOf(f) //reflect.Value
//第一引数の型を取得
argType := fv.Type().In(0) //reflect.Type
//mode=trueの時、int64
//mode=falseの時、uint64
fmt.Println(argType.Kind())
//func (v Value) Convert(t Type) Value
result := fv.Call([]reflect.Value{reflect.ValueOf(100).Convert(argType), reflect.ValueOf(10)})
fmt.Println(result[0])
//mode=trueの時、int64
//mode=falseの時、uint64
fmt.Println(reflect.ValueOf(100).Convert(argType).Kind())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment