Go: How can I create a global variable to hold anything?

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

Go: How can I create a global variable to hold anything?

问题

我很好奇如何创建一个全局变量,在需要时可以被赋予任何值。以下是我的情况:

我需要等待从服务器发出的事件,该事件发送一个填充了结构体的数据,并且我想将该数据赋给一个已创建的变量:

func NewCS(client *thing.Thing) *structThing {

}

但是 *structThing 没有被导出,所以我不能这样做:

var cs *structThing

// 事件最终准备好
cs = NewCS(eventData)

因为我会得到 *structThing 未导出的错误。

那么,我还有其他方法可以将 cs 变成全局变量吗?

英文:

I'm curious on how to create a global variable that can be assigned to be anything when the chance comes, here's my scenario:

I have to wait for an event that emits from a server that sends a populated struct, and I want to assign that to a variable the struct is created with:

func NewCS(client *thing.Thing) *structThing {

}

But the *structThing is not exported so I can't do

var cs *structThing

// Event finally ready
cs = NewCS(eventData)

because I get the error that *structThing is not exported.

So how else can I make cs a global variable?

答案1

得分: 5

你可以将其存储在一个类型为interface{}的变量中。

package main

import "fmt"

type structThing struct {
    x int
}

func NewCS() *structThing {
    return &structThing{x: 1}
}

var cs interface{}

func main() {
    fmt.Println("cs is", cs)
    cs = NewCS()
    fmt.Println("cs is now", cs)
}

输出结果为:

cs is <nil>
cs is now &{1}

链接:https://play.golang.org/p/ZW_6FRfDvE

英文:

You can store it in an variable typed as an interface{}.

package main

import &quot;fmt&quot;

type structThing struct {
	x int
}

func NewCS() *structThing {
	return &amp;structThing{x: 1}
}

var cs interface{}

func main() {
	fmt.Println(&quot;cs is&quot;, cs)
	cs = NewCS()
	fmt.Println(&quot;cs is now&quot;, cs)
}

Which prints:

cs is &lt;nil&gt;
cs is now &amp;{1}

https://play.golang.org/p/ZW_6FRfDvE

huangapple
  • 本文由 发表于 2015年11月19日 06:42:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/33791874.html
匿名

发表评论

匿名网友

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

确定