Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang get the reflect.Type of a type

Tags:

reflection

go

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)

What in java will be: MyType.class

like image 539
gsf Avatar asked May 26 '16 18:05

gsf


People also ask

How do I print type in Go?

🤔 Print type of variable in Go To print a variable's type, you can use the %T verb in the fmt. Printf() function format. It's the simplest and most recommended way of printing type of a variable. Alternatively, you can use the TypeOf() function from the reflection package reflect .

How a variable type is checked at runtime in Go language?

A quick way to check the type of a value in Go is by using the %T verb in conjunction with fmt. Printf . This works well if you want to print the type to the console for debugging purposes.


1 Answers

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

Also, it's demonstrated in the reflect example here; https://golang.org/pkg/reflect/#example_TypeOf

like image 107
evanmcdonnal Avatar answered Oct 02 '22 03:10

evanmcdonnal