duanfu5239 2019-08-19 23:13
浏览 60

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>
  • 写回答

1条回答 默认 最新

  • douzhuo1858 2019-08-19 23:25
    关注

    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()

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题