英文:
Populate a nil struct inside its method
问题
我不知道在Go语言中是否可能实现这个,但是如果我在一个空结构体上调用一个方法,有没有办法填充它呢?
这是我尝试做的事情:
type A struct {
Name string
}
func (a *A) DoStuff() {
if a == nil {
a = &A{Name: "hello"}
}
}
func main() {
var a *A
a.DoStuff()
println(a.Name) // 希望输出"hello"
}
但是上面的代码并没有填充a
为A{}
的实例,这可能是预期的结果。
有没有一些技巧可以实现这个,还是说根本不可能?
提前感谢!
英文:
I don't know if this is possible in Go, but if I call a method on a nil struct, is there a way to populate it?
Here's what I'm trying to do:
type A struct {
Name string
}
func (a *A) DoStuff() {
if a == nil {
a = &A{Name: "hello"}
}
}
func main() {
var a *A
a.DoStuff()
println(a.Name) // want "hello"
}
but the above does not populate a
with an instance of A{}
, which is probably expected.
Is there some trick to accomplish this or is it just not possible?
Thanks in advance!
答案1
得分: 3
TL;DR,你不能这样做。在你的方法中,a
是一个局部变量。当你执行:
a := &A{}
你正在用一个指向新结构体的新指针覆盖局部变量。你想要的是覆盖现有指针指向的新结构体。唯一的方法是对指针进行解引用:
*a := A{}
但是你不能对一个nil
指针进行解引用,因为它不指向任何东西;没有为它分配内存,你的应用程序将崩溃。
英文:
TL;DR, you can't. In your method, a
is a local variable. When you do:
a := &A{}
You're overwriting the local variable with a new pointer to a new struct. What you want is to overwrite the existing pointer to a new struct. The only way to do that is to dereference the pointer:
*a := A{}
But you can't dereference a nil
pointer, because it doesn't point to anything; no memory is allocated for it, and your application will crash.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论