I'd like to get (reflect)type from type name.
http://play.golang.org/p/c-9IpSafx0
package main
import (
"fmt"
"reflect"
)
type Name string
func main() {
fmt.Println("Hello, playground")
var name Name = "Taro"
fmt.Println(name)
fmt.Println(getType(name))
// fmt.Println(getType(Name)) // want to same as getType(name)
}
func getType(v interface{}) reflect.Type {
return reflect.TypeOf(v)
}
How do I rewrite getType function.
There is no way to pass a type as an argument to a function in Go, so what you ask is not possible. If you want to use the reflect
module to work with types, you will need to have a value as a starting point.
As @James Henstridge said, you can't pass a type to a function in go. However if you have a composite type then you can create a nil
version of it very easily and pass that instead. (play)
type Name struct{ name string }
func main() {
var name = Name{"Taro"}
fmt.Println(name)
fmt.Println(getType(name))
fmt.Println(getType(Name{})) // want to same as getType(name)
}
func getType(v interface{}) reflect.Type {
return reflect.TypeOf(v)
}
That said, I can't see why you'd want to do this, since you know what type you've got when you pass it into the getType()
function, so you know its name, so why not just use it?