Go中如何设置一个单例状态? (或者,为什么这不起作用?)

This question already has an answer here:

Barring any conversation about whether singletons should be used (Yes, I know, antipattern, I've opted not to use it anyway), I'm confused as to why this doesn't work. I have state I'm trying to set within a singleton instance, but my method is not actually modifying the main instance.

What does hold is any initialization I pass when the singleton is instantiated.

At first I thought it was a nested struct problem, because I started with a bar in a foo, but then found it did the same thing with the primitive val.

In the off chance it matters, I'm running Go 1.12.7 on Mac OS Mojave.

package main

import (
    "fmt"
    "sync"
)

type foo struct {
    val   int
    state bar
}

type bar struct {
    inner int
}

var singleton *foo
var once sync.Once

func GetFoo() *foo {
    once.Do(func() {
        singleton = &foo{
            state: bar{inner: 0},
        }
    })
    return singleton
}

func (f foo) SetState() {
    f.val = 1
    f.state.inner = 1
}

func main() {

    f := GetFoo()
    fmt.Println(f)
    f.SetState()
    fmt.Println(f)

}

I would expect this to output:

&{0 {0}}
&{1 {1}}

Instead, I'm getting:

&{0 {0}}
&{0 {0}}
</div>

Cerise spotted it immediately. I did not realize method receivers are essentially passed by value in Go. Therefore, to fix this example, the SetState signature just needs to be changed to (f *foo) SetState()