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"
}
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.
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.
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.
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.
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
}
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 ()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With