简体   繁体   English

golang得到一个类型的reflect.Type

[英]golang get the reflect.Type of a type

Is it possible and how to get the reflect.Type of a type without creating an object from the type and calling on it reflect.TypeOf(obj) 是否有可能以及如何获取类型的reflect.Type而不从类型创建对象并调用它reflect.TypeOf(obj)

What in java will be: MyType.class java中的内容: MyType.class

You can achieve this without an instantiation with the following syntax; 您可以在没有使用以下语法的实例化的情况下实现此目的;

package main

import (
    "fmt"
    "reflect"
)

type Test struct {
}


func main() {
    fmt.Println(reflect.TypeOf((*Test)(nil)).Elem())
}

play; 玩; https://play.golang.org/p/SkmBNt5Js6 https://play.golang.org/p/SkmBNt5Js6

Also, it's demonstrated in the reflect example here; 此外,它在这里的反映例子中得到了证明; https://golang.org/pkg/reflect/#example_TypeOf https://golang.org/pkg/reflect/#example_TypeOf

No you can't have it directly, because in Go structs have no accessible fields to get their type. 不,你不能直接拥有它,因为在Go结构中没有可访问的字段来获取它们的类型。

One may think of tweaking it by doing the following: 可以考虑通过执行以下操作来调整它:

type object struct {}

func main() {
    var obj object
    t := reflect.TypeOf(object)
    fmt.Println(t)
    // main.object
}

However, in Go every variable is initialized with its zero value , so this is perfectly equivalent to: 但是,在Go中,每个变量都以零值初始化,因此这完全等同于:

t := reflect.TypeOf(object{})
// main.object

If you look at Golang's source code, you'll see that reflect.Type is an interface implemented differently according to types, however you do not have access to those informations. 如果你看一下Golang的源代码,你会发现reflect.Type是一个根据类型实现不同的接口,但你无法访问这些信息。

But, what you can do is get the type of a pointer to the struct and from there, get the actual type. 但是,您可以做的是获取指向结构的指针的类型,然后从中获取实际类型。 The process is the same, except that a pointer's zero value is nil , so it takes less time to instantiate: 除了指针的零值为nil之外,该过程是相同的,因此实例化所需的时间更少:

func main() {
    ptr_t := reflect.TypeOf((*object)(nil))
    fmt.Println(ptr_t)
    // *main.object

    t := ptr_t.Elem()
    fmt.Println(t)
    // main.object
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM