In go, how do I make global variables

package main import ( "fmt" "bufio" "os" ) func main() { fmt.Print("LOADED!\n") fmt.Print("insert y value here: ") inputY := bufio.NewScanner(os.Stdin) inputY.Scan() inputXfunc() } func inputXfunc() { fmt.Print("insert x value here: ") inputX := bufio.NewScanner(os.Stdin) inputX.Scan() slope() } func slope() { fmt.Println(inputX.Text()) } 

Whenever I run this program, it says that inputX and inputY are not identified. How to make this program use variables available for all functions? All I want to do is split inputY by inputX and print the result

+5
source share
2 answers

I just put my comment as an answer ... I would recommend against this, but you could just declare a variable in the package scope. It will look like this:

 package main import ( "fmt" "bufio" "os" ) var inputX io.Scanner func main() { fmt.Print("LOADED!\n") fmt.Print("insert y value here: ") inputY := bufio.NewScanner(os.Stdin) inputY.Scan() inputXfunc() } func inputXfunc() { fmt.Print("insert x value here: ") inputX = bufio.NewScanner(os.Stdin) // get rid of assignment initilize short hand here inputX.Scan() slope() } func slope() { fmt.Println(inputX.Text()) } 

However, a better choice would be to change the definitions of the methods for accepting the arguments and pass the values ​​to them as needed. It would be like this:

 func slope(inputX bufio.Scanner) { fmt.Println(inputX.Text()) } slope(myInputWhichIsOfTypeIOScanner) 
+7
source

You can create the init() function and use it in main.go with a package like godotenv to set the os environment variables:

global.go file

 package global import ( "log" "os" "strconv" "github.com/joho/godotenv" ) var ( SERVER_HOST string SERVER_PORT int ) func InitConfig() { err := godotenv.Load() if err != nil { log.Fatal("Error loading .env file") } SERVER_HOST = os.Getenv("SERVER_HOST") SERVER_PORT, _ = strconv.Atoi(os.Getenv("SERVER_PORT")) } 

main.go file

 package main import( G "path/to/config" ) func init() { G.InitConfig() } func main() { G.Init() } 

You still have to import the β€œG” package into other packages to use the variables, but I believe that the best way to solve global variables in Go (or any other languages) is to use environment variables.

+1
source

Source: https://habr.com/ru/post/1236759/


All Articles