doujiong2533 2018-01-09 16:48
浏览 715

Golang中的静态全局变量

I am new in Go language and I need some help. I have declared a global variable but the problem is that it does not keep its value. It would be solved with a static variable but no such variables exist in Go. How should I solve this?

gID is a global variable. This function is called twice. On the first call if code is executed. On the second, else code is executed. I want the second struct Learner instance, to get first Learner's instance ID.

I have to mention that NewLearner is called twice from two different files from different packages.

func NewLearner(name string, peerURLs types.URLs, clusterName string, now *time.Time) *Learner {

    l := &Learner{
        RaftAttributes: RaftAttributes{PeerURLs: peerURLs.StringSlice()},
        Attributes:     Attributes{Name: name},
    }

    var b []byte
    sort.Strings(l.PeerURLs)
    for _, p := range l.PeerURLs {
        b = append(b, []byte(p)...)
    }

    b = append(b, []byte(clusterName)...)
    if now != nil {
        b = append(b, []byte(fmt.Sprintf("%d", now.Unix()))...)
        hash := sha1.Sum(b)
        l.ID = types.ID(binary.BigEndian.Uint64(hash[:8]))
        gID=l.ID
        return l
    }  else {
        l.ID = gID
        return l    
    }

}
  • 写回答

2条回答 默认 最新

  • dongren9966 2018-01-09 22:46
    关注

    The fact that the package variable doesn't keep its value might be caused by concurrency. I would solve your problem that way. Use a package variable with a mutex around in case the function is called concurrently.

    import "sync"
    
    var(
        gID  uint64
        muID sync.Mutex
    )
    
    func myfunc(param bool) {
        var id uint64
        if param {
            id = newID()
    
            muID.Lock()
            gID = id
            muID.Unlock()
        } else {
            muID.Lock()
            id = gID
            muID.Unlock()
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?