获取 reflect.Type 的指针类型。

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

Get pointer type of a reflect.Type

问题

假设我只有一个 reflect.Type 类型的变量 t

fmt.Println(t) // 输出 lib.Counter

我想要获取该类型的指针类型,使得:

fmt.Println(ptrT) // 输出 *lib.Counter

我该如何做到这一点?t 可以是任何类型,不仅限于 lib.Counter

另外,如果我想要反过来做呢?比如从 *lib.Counter 获取 lib.Counter

英文:

Assume I only have a reflect.Type t:

fmt.Println(t) //prints lib.Counter

I would like to get pointer type to this type, such that:

fmt.Println(ptrT) //prints *lib.Counter

How can I do this? t can be of any type, not only lib.Counter.

Also, what if I want to do vice versa? Like getting lib.Counter from *lib.Counter?

答案1

得分: 2

你可以使用reflect.PointerTo

要再次获取非指针类型,可以使用Type.Elem()

thing := Thing{}
ptrThing := &Thing{}

thingType := reflect.TypeOf(thing)
fmt.Println(thingType) // main.Thing
thingTypeAsPtr := reflect.PointerTo(thingType)
fmt.Println(thingTypeAsPtr) // *main.Thing

ptrThingType := reflect.TypeOf(ptrThing)
fmt.Println(ptrThingType) // *main.Thing
ptrThingTypeAsNonPtr := ptrThingType.Elem()
fmt.Println(ptrThingTypeAsNonPtr) // main.Thing

工作示例:https://go.dev/play/p/29eXtdgI9Xf

英文:

You can use reflect.PointerTo.

To get the non-pointer type again, you can use Type.Elem().

thing := Thing{}
ptrThing := &Thing{}

thingType := reflect.TypeOf(thing)
fmt.Println(thingType) // main.Thing
thingTypeAsPtr := reflect.PointerTo(thingType)
fmt.Println(thingTypeAsPtr) // *main.Thing

ptrThingType := reflect.TypeOf(ptrThing)
fmt.Println(ptrThingType) // *main.Thing
ptrThingTypeAsNonPtr := ptrThingType.Elem()
fmt.Println(ptrThingTypeAsNonPtr) // main.Thing

Working example: https://go.dev/play/p/29eXtdgI9Xf

答案2

得分: 0

你可以通过以下方式实现:

ptr := reflect.PointerTo(reflect.TypeOf(lib.Counter{})) // *lib.Counter

变量 t 可以是任意类型:

ptr := reflect.PointerTo(t)
英文:

You can achieve that in the following way:

ptr := reflect.PointerTo(reflect.Typeof(lib.Counter{})) // *lib.Counter

The variable t can be an arbitrary type:

ptr := reflect.PointerTo(t)

huangapple
  • 本文由 发表于 2022年7月15日 03:13:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/72985583.html
匿名

发表评论

匿名网友

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

确定