Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access variables in other package

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" 
}
like image 534
Patryk Gtfo Avatar asked Sep 17 '16 17:09

Patryk Gtfo


People also ask

Does Go have global variables?

A global variable refers to a variable that is defined outside a function. Global variables can be accessed throughout the program or within any function in the defined package. Follow us along as we explore the concept of global variables in the go programming language.

How do you define a global variable in go?

Global variables are defined outside of a function, usually on top of the program. Global variables hold their value throughout the lifetime of the program and they can be accessed inside any of the functions defined for the program. A global variable can be accessed by any function.

What does Go init do?

The init Function This effectively allows us to set up database connections, or register with various service registries, or perform any number of other tasks that you typically only want to do once. package main func init() { fmt. Println("This will get called on main initialization") } func main() { fmt.

Can we import main package in Golang?

You cannot import the main package. Any shared code should go in a separate package, which can be imported by main (and other packages). See also groups.google.com/forum/#! topic/Golang-nuts/frh9zQPEjUk for discussion.


2 Answers

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
}
like image 160
dave Avatar answered Sep 30 '22 00:09

dave


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 ()
like image 24
ASH Avatar answered Sep 30 '22 00:09

ASH