Created
October 9, 2013 03:30
-
-
Save kwmt/6895772 to your computer and use it in GitHub Desktop.
#golang リフレクションを使って、キャストする。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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