我是 Go 语言新手,我需要一些帮助。我已经声明了一个全局变量,但问题是它不保留其值。可以用静态变量来解决,但 Go 中不存在这样的变量。我该如何解决这个问题?

gID
是一个全局变量。该函数被调用两次。第一次调用
if
代码就会被执行。第二个,执行
else
代码。我想要第二个 struct
Learner
实例来获取第一个学习者的实例 ID。

我不得不提的是,NewLearner 被来自不同包的两个不同文件调用了两次

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    
    }

}