Check type of struct in Go

Viewed 17545

I'm trying to check the type of a struct in Go. This was the best way I could come up with. Is there a better way to do it, preferably without initializing a struct?

package main

import (
    "fmt"
    "reflect"
)

type Test struct{
    foo int
}

func main() {
    t := Test{5}
    fmt.Println(reflect.TypeOf(t) == reflect.TypeOf(Test{}))
}
3 Answers

You can simply assign t to an empty interface variable and check its type

and you don't need to necessarily write a function to check this out.

var i interface{} = t
v, ok := i.(Test)
//v = concrete value of Test struct
//ok = is (t) a type of the Test struct?
Related