Go:我如何创建一个全局变量来保存任何东西?

Dat*_*sik 0 go

我很好奇如何创建一个全局变量,当有机会时可以将其分配给任何东西,这是我的场景:

我必须等待从发送填充结构的服务器发出的事件,并且我想将其分配给创建结构的变量:

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

}
Run Code Online (Sandbox Code Playgroud)

但是*structThing没有出口所以我做不到

var cs *structThing

// Event finally ready
cs = NewCS(eventData)
Run Code Online (Sandbox Code Playgroud)

因为我得到了*structThing未导出的错误.

那么我怎样才能创建cs一个全局变量呢?

Dou*_*son 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)
}
Run Code Online (Sandbox Code Playgroud)

哪个印刷品:

cs is <nil>
cs is now &{1}
Run Code Online (Sandbox Code Playgroud)

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