Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a struct has struct embedding at run time

Tags:

go

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?

like image 836
huggie Avatar asked May 08 '26 11:05

huggie


2 Answers

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.

like image 75
blami Avatar answered May 11 '26 16:05

blami


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

like image 35
mkopriva Avatar answered May 11 '26 15:05

mkopriva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!