嵌入式带有接口的结构不起作用。

huangapple go评论134阅读模式
英文:

Embedded Structure with interface not working

问题

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

如何使其能够获取基本结构和继承结构的返回值?

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())    
}
英文:

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

答案1

得分: 2

方法SetId使用了值接收器,所以p是对象的副本,而不是指向对象的指针。

相反,你应该使用指针接收器,如下所示:

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

你可以在Go之旅的选择值或指针接收器部分找到更多详细信息。

英文:

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.

huangapple
  • 本文由 发表于 2021年8月23日 16:23:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/68889400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定