在init函数内部分配的值无法保持其值。

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

Value assigned inside init doesnt maintain the value

问题

我正在使用Golang进行开发,对于func init()的工作原理有些困惑。假设我有两个包,分别叫做mainpkg2。在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.

huangapple
  • 本文由 发表于 2017年4月27日 08:03:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/43646485.html
匿名

发表评论

匿名网友

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

确定