go - 如何访问其他包中的变量

标签 go package global-variables

如何将我的全局变量移动到 Go 中的其他包?

喜欢

package main
import "myapp/controllers"

var something string

func main(){ 
  something = "some text" 
}

最佳答案

就像你想在你的包 controllers 中有一个全局可访问的变量?:

package controllers

var Something string
var SomethingElse string = "whatever"

func init(){ 
    Something = "some text" 
}

然后你可以做

package main
import (
    "myapp/controllers"
    "fmt"
)

func main(){ 
    fmt.Println(controllers.Something, controllers.SomethingElse) //some text
}

关于go - 如何访问其他包中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39549775/

相关文章:

go - 如何在Go中将DB连接初始化作为一个包分开?

android - 请安装包 : 'Android Support Library'

node.js - 错误 : ENOENT, 统计 'C:\Users\Ali\AppData\Roaming\npm'

c++ - 如何定义多个源文件访问的linux内核变量?

wolfram-mathematica - 列出所有全局变量

linux - net.DialTCP 在 Linux 上产生 "connection refused"错误,但在 Windows 上没有

golang 有效地处理 Null* 类型

mysql - 有正确的方法连接到MySQL吗?

package - `ERROR: EOFError: read end of file` 安装新 Julia 版本后使用包时

c - 跨模块的全局变量