Sredny M Casanova
Sredny M Casanova

Reputation: 5053

Value assigned inside init doesnt maintain the value

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!

Upvotes: 0

Views: 58

Answers (1)

Peyman Mahdian
Peyman Mahdian

Reputation: 522

I believe you should change := to =, because that way you are introducing a new var.

Upvotes: 5

Related Questions