首页 > 解决方案 > 带有接口的嵌入式结构不起作用

问题描述

下面的代码无法从基本实体设置或获取值

如何使其工作以获取基础和继承的结构以返回值

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())     
}

标签: gostructinterfacebase

解决方案


该方法SetId使用值接收器,因此p是对象的副本,而不是指向对象的指针。

相反,您想使用指针接收器,如下所示:

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

您可以在选择值或指针接收器部分的 Go Tour of Go 中找到更多详细信息。


推荐阅读