liam
liam

Reputation: 361

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 unidentified. How do I make this program use variables that are accessible to all of the functions? All I want to do is devide inputY by inputX then print out the result

Upvotes: 7

Views: 29650

Answers (2)

Pandemonium
Pandemonium

Reputation: 8390

You can create an init() function and make use of it in the main.go by using package like godotenv to set os's 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 will still have to import "G" package in other packages to use the variables, but I think the best way to tackle global variables in Go (or any other languages) is to make use of environment variables.

Upvotes: 3

evanmcdonnal
evanmcdonnal

Reputation: 48154

I'm just putting my comment as an answer... I would recommend against this however you could just declare the variable at package scope. It would 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 your method definitions to accept arguments and pass the values into them as needed. This would like like so;

func slope(inputX bufio.Scanner) {
        fmt.Println(inputX.Text())
    }

 slope(myInputWhichIsOfTypeIOScanner)

Upvotes: 8

Related Questions