lundi 29 juillet 2019

Is there a way to read top-level struct type using method defined in embedded struct? [duplicate]

This question already has an answer here:

To satisfy some interface, I need to add a method to every object, kind of like adding trait in object oriented languages.

The plan is to create base struct with such method and to embed it into other structs, which are sometimes embedded to another structs and so on.

package main

import (
    "fmt"
    "reflect"
)

type BaseStruct struct {
}

func (this BaseStruct) InterfaceMethod() {
    str := reflect.TypeOf(this).String()
    fmt.Println(fmt.Sprintf("%s", str))
}

type StructA struct {
    BaseStruct
}

func main() {
    baseStruct := BaseStruct{}
    structA := StructA{}

    baseStruct.InterfaceMethod()
    structA.InterfaceMethod()

}

Current output:

main.BaseStruct
main.BaseStruct

Desired output:

main.BaseStruct
main.StructA 

Is there any way to check if struct is embedded in other struct, traverse through them up the top and read top-level struct name?

Go playground link: https://play.golang.org/p/794lneEtByS





Aucun commentaire:

Enregistrer un commentaire