简体   繁体   中英

Check type of struct in Go

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{}))
}

Type assertions:

package main

import "fmt"

type Test struct {
    foo int
}

func isTest(t interface{}) bool {
    switch t.(type) {
    case Test:
        return true
    default:
        return false
    }
}

func main() {
    t := Test{5}
    fmt.Println(isTest(t))
}

Playground


And, more simplified:

_, isTest := v.(Test)

Playground


You can refer to the language specification for a technical explanation.

You may pass a "typed" nil pointer value to reflect.TypeOf() , and call Type.Elem() to get the type of the pointed value. This does not allocate or initialize a value of the type (in question), as only a nil pointer value is used:

fmt.Println(reflect.TypeOf(t) == reflect.TypeOf((*Test)(nil)).Elem())

Try it on the Go Playground .

PS This is an exact duplicate, but can't find the original.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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