Search code examples
gostructinterfaceradix

Embedded Structure with interface not working


Below code not able to set or get the values from base entity

How to make it working to get base as well as inherited struct to return values

type BaseEntity struct {
    Id string
}

func (p BaseEntity) SetId(Id string) {
    p.Id = Id
}

func (p BaseEntity) GetId() string { 
    return p.Id
}

type Employee struct {
    BaseEntity
    Name string
}

type DataInterface interface {
    SetId(Id string)
    GetId() string  
}

func getObjFactory() DataInterface {
    //return Data.Employee{BaseEntity: Data.BaseEntity{}}
    return new(Employee)
}

func main() {   
    entity := getObjFactory()

    entity.SetId("TEST")
    fmt.Printf(">> %s", entity.GetId())     
}

Solution

  • The method SetId is using a value receiver so p is a copy of the object as opposed to a pointer to the object.

    Instead, you want to use a pointer receiver as below:

    func (p *BaseEntity) SetId(Id string) {
        p.Id = Id
    }
    

    You can find more details in the Tour of Go under section Choosing a value or pointer receiver.