英文:
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 "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)
}
Which prints:
cs is <nil>
cs is now &{1}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论