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