在其方法中填充一个空结构体。

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

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"
}

但是上面的代码并没有填充aA{}的实例,这可能是预期的结果。

有没有一些技巧可以实现这个,还是说根本不可能?

提前感谢!

英文:

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.

huangapple
  • 本文由 发表于 2021年8月10日 23:30:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/68729658.html
匿名

发表评论

匿名网友

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

确定