0

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

Aśtar Sheran
  • 91
  • 1
  • 4
  • This is not possible in Go. If you need to know about who embeds a value, you must maintain that value yourself (e.g. the embedded value must have a parent field). – icza Jul 29 '19 at 12:17
  • Ok, then I'll have to go with some other solution. Thank you for super-fast response and linking to similar question – Aśtar Sheran Jul 29 '19 at 12:22

0 Answers0