如何获取类型

huangapple go评论94阅读模式
英文:

How do I get Type

问题

你想要从类型名称中获取(反射)类型。以下是重写getType函数的方法:

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))  // 希望与getType(name)的结果相同
}

func getType(v interface{}) reflect.Type {
	switch v.(type) {
	case Name:
		return reflect.TypeOf(Name(""))
	default:
		return reflect.TypeOf(v)
	}
}

在重写的getType函数中,我们使用了类型断言(type assertion)来判断v的具体类型。如果v的类型是Name,则返回reflect.TypeOf(Name("")),否则返回reflect.TypeOf(v)。这样就可以实现与getType(name)相同的结果。

英文:

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.

答案1

得分: 2

在Go语言中,无法将类型作为参数传递给函数,所以你所问的是不可能的。如果你想使用reflect模块来处理类型,你需要有一个值作为起点。

英文:

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.

答案2

得分: 0

如@James Henstridge所说,你不能在Go中将类型传递给函数。但是,如果你有一个复合类型,你可以很容易地创建一个nil版本,并将其传递给函数。(play)

type Name struct{ name string }

func main() {
    var name = Name{"Taro"}
    fmt.Println(name)

    fmt.Println(getType(name))
    fmt.Println(getType(Name{})) // 希望与getType(name)相同
}

func getType(v interface{}) reflect.Type {
    return reflect.TypeOf(v)
}

话虽如此,我看不出为什么你要这样做,因为当你将其传递给getType()函数时,你知道你拥有的类型,所以你知道它的名称,为什么不直接使用它呢?

英文:

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?

huangapple
  • 本文由 发表于 2014年2月6日 09:14:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/21592111.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定