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