Let's say I have the following struct:
type Room struct {
BaseModel
}
func main() {
r := Room{}
}
Say elsewhere in the code I obtained an object r. It could be Room or something else. I want to check during runtime if r's class, in this case Room, has a struct embedding of BaseModel. Is that possible?
Yes, you can check that in runtime by using reflection. Here's very simple example that uses reflect.TypeOf to print type of each field of struct Bar that embeds struct Foo and also reflect.ValueOf to print whether field is anonymous (true) or not - which is a good indicator of what you ask for:
package main
import (
"fmt"
"reflect"
)
type Foo struct {
foo string
}
type Bar struct {
Foo
bar string
}
func main() {
test := Bar{}
t := reflect.TypeOf(test)
for i := 0; i < t.NumField(); i++ {
fmt.Print(t.Field(i).Type, " ")
fmt.Println(reflect.ValueOf(t.Field(i).Anonymous))
}
}
Here is code on playground: https://play.golang.org/p/zNWxZUzq_RS
You don't ask what exactly you want to do with that information so pointing you to reflect documentation for more advanced use.
Check the Anonymous field of reflect.StructField.
func embedsBaseModel(v interface{}) bool {
rt := reflect.TypeOf(v)
if rt.Kind() != reflect.Struct {
return false
}
base := reflect.TypeOf(BaseModel{})
for i := 0; i < rt.NumField(); i++ {
if sf := rt.Field(i); sf.Type == base && sf.Anonymous {
return true
}
}
return false
}
https://play.golang.com/p/-6flZcdSYwj
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