go - 带有接口的嵌入式结构不起作用
问题描述
下面的代码无法从基本实体设置或获取值
如何使其工作以获取基础和继承的结构以返回值
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())
}
解决方案
该方法SetId
使用值接收器,因此p
是对象的副本,而不是指向对象的指针。
相反,您想使用指针接收器,如下所示:
func (p *BaseEntity) SetId(Id string) {
p.Id = Id
}
您可以在选择值或指针接收器部分的 Go Tour of Go 中找到更多详细信息。
推荐阅读
- java - 无法使用使用 HTTPS 的 AWS S3 Java API 访问 S3 上的存储桶
- java - 如何使用firebase登录令牌?
- python - 使用 Python 在多个网站中自动填写表单
- excel - 当所有未完成的引用都消失时,如何确保 Excel 将关闭
- reactjs - 酶浅渲染子组件,包升级时的行为改变
- java - 是否可以在 javaee 应用程序中具有相同的界面并在 CLI 和 GUI 中使用它?
- angular - 将使用 `this` 关键字的函数从组件移动到共享服务
- ruby-on-rails - 如何确定从 ApplicationController 调用了哪个控制器?
- javascript - 控制器未从 Lightning 组件初始化处理程序接收对象
- javascript - 如何并行执行两个异步函数然后等待它们完成?