英文:
Value assigned inside init doesnt maintain the value
问题
我正在使用Golang进行开发,对于func init()
的工作原理有些困惑。假设我有两个包,分别叫做main
和pkg2
。在main
包中,我试图调用pkg2
包中的一个变量,但是它返回的是nil。基本上,代码结构如下:
Main包:
import (
...
"github.com/myproject/config/pkg2"
)
func main() {
if pkg2.MyVariable == nil {
// 它是nil。并且它进入了这个条件语句,我不知道为什么
}
}
PKG2包:
package pkg2
import (
...一些导入...
)
var MyVariable
func init() {
MyVariable := "something"
// 在这里给MyVariable赋值
// 我在这里设置了一个if语句来检查是否执行
// MyVariable正确地获得了一个值
}
我还注意到init函数
在我调用pkg2.MyVariable
之前就已经执行了。所以,简而言之:在main包中它返回的是nil,但在init函数中,值被正确赋值了,为什么它会再次变成nil呢?我漏掉了什么?谢谢!
英文:
I'm working on Golang and am a little confused about how the func init()
works. Lets's say that I have 2 packages called main
and pkg2
inside main I am trying to call a variable that is inside pkg2 but its giving me nil. Basically this is the structure:
Main Package:
import (
...
"github.com/myproject/config/pkg2"
)
func main () {
if pkg2.Myvariable == nil {
//it's nil. And it's entering in this conditional don't know why
}
}
PKG2 Package:
package pkg2
import (
...some imports...
)
var MyVariable
func init () {
MyVariable := "something"
//Here I assign a value to MyVariable
//I set an if here to check if it's executed
//and MyVariable get a value correctly
}
I also noticed that the init function
is executed before I even call pkg2.Myvariable
. So, briefly: inside main package it's given nil, but inside init the value is assigned correctly, why then it return to nil?
What Am I missing? Thank you!
答案1
得分: 5
我认为你应该将:=
改为=
,因为这样你就引入了一个新的变量。
英文:
I believe you should change :=
to =
, because that way you are introducing a new var.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论