如何访问其他包中的变量

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

How to access variables in other package

问题

你可以将全局变量移动到其他Go包中。例如:

package main

import (
    "myapp/controllers"
)

var something string

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

请注意,如果你想在其他包中访问该全局变量,你需要将其导出。在Go中,以大写字母开头的标识符是可导出的,小写字母开头的标识符是私有的。所以,如果你想在其他包中访问something变量,你可以将其改为Something

英文:

How can I move my global variable to other package in Go?

like

package main
import "myapp/controllers"

var something string

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

答案1

得分: 10

你想在你的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
}
英文:

Like you want to have a globally accessible variable in your package controllers?:

package controllers

var Something string
var SomethingElse string = "whatever"

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

And then you can do

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

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

答案2

得分: 10

只是为了补充Dave的回答,并提到另一个可能的问题。
变量名需要以大写字母开头才能可见。

package main
import "myapp/controllers"

var Something string

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

此外,如果您在go.mod文件中的模块名称不正常,可能会遇到问题。在这个例子中,它应该类似于这样

module myapp

go 1.16

require ()
英文:

Just to add onto Daves answer, and another possible issue you were having.
Variable names need to be Start With A Capital Letter To Be Visible

package main
import "myapp/controllers"

var Something string

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

Additonally, you might have issues if you module name in go.mod file is weird. In this example it should look something like this

module myapp

go 1.16

require ()

huangapple
  • 本文由 发表于 2016年9月18日 01:29:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/39549775.html
匿名

发表评论

匿名网友

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

确定