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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With