当无法控制父结构的初始化时,如何初始化嵌套结构?

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

Initializing embedded struct when no control over parent initialization

问题

我有一个这样的结构体:

type Parent struct {
  *WithContext
}

type WithContext struct {
  Ctx context.Context
}

func (wi *WithContext) SetContext(ctx context.Context) {
  // 空指针
  wi.Ctx = ctx
}

Parent是通过某个自动化过程(作为解组流程的一部分)进行初始化的,所以我无法初始化嵌入的WithContext结构体。

有没有办法避免在'SetContext'函数中出现空指针?我尝试重写指针接收器,但没有任何效果。

谢谢,

Asaf.

英文:

I have a struct such:

type Parent struct {
  *WithContext
}

type WithContext struct {
  Ctx context.Context
}

func (wi *WithContext) SetContext(ctx context.Context) {
  // nil pointer
  wi.Ctx = ctx
}

Parent is initialized by some automated process (as apart of unmarshalling flow), so I cannot initialize the embedded WithContext struct,

Is there any way to avoid the nil pointer in the 'SetContext' func ? I tried overriding the pointer receiver but it doesn't have any effect,

Thanks,

Asaf.

答案1

得分: 1

理想情况下,构造Parent结构的任何内容都应该初始化它,使其处于可用状态。但由于您无法控制它,下一个最好的方法是编写一段代码,让您可以设置Parent中的WithContext指针,可以通过在Parent上提供一个成员函数或者在应用程序中提供一段代码来设置它,因为WithContext字段是公开的。

英文:

Ideally, whatever is constructing the Parent struct should initialize it so it's in a usable state. But since you have no control over it, the next best thing is to have a piece of code that lets you set the WithContext pointer in Parent, by providing a member function on Parent or just a piece of code in your application to set it, since WithContext field is exported.

huangapple
  • 本文由 发表于 2016年12月26日 22:08:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/41332454.html
匿名

发表评论

匿名网友

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

确定