英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论