Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check type of struct in Go

Tags:

reflection

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{}))
}
like image 872
ollien Avatar asked Dec 01 '22 11:12

ollien


1 Answers

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.

like image 96
Emile Pels Avatar answered Dec 04 '22 14:12

Emile Pels