0

I have the following code:

package main

import (
  "net/http"
  "log"
  "net"
  "fmt"
  "os"
  "encoding/json"
)

const configName string = "config.json"

type Config struct {
 UDPServerAddress string
 HTTPServerAddress string 
}

var config Config

func UDProutine (query string, ch chan<- string) {
  log.Fatal(config.UDPServerAddress)
}

func main () {
  file,_ := os.Open(configName)
  defer file.Close()
  decoder := json.NewDecoder(file)
  config := Config{}
  err := decoder.Decode(&config)
  if err != nil {
     fmt.Println("error",err)
  }
  log.Fatal(config.UDPServerAddress)
}

And in my config.json

{
  "UDPServerAddress":"127.0.0.1:54",
  "HTTPServerAddress":"127.0.0.1:8082"
}

My question is, why does it log the config data correctly inside main but its empty value when logged inside UDPRoutine

icza
  • 389,944
  • 63
  • 907
  • 827
somejkuser
  • 8,856
  • 20
  • 64
  • 130

1 Answers1

1

Inside main() you used the same name: config for a local variable. This will shadow the global variable. After this point, you can't refer to the global variable (for details, see Refer to constant or package level variable instead of function level variable). You load the config into this local variable, but the global config will remain unchanged (zero), and the UDProutine() function will read / print this global variable.

If you want to load the config to the global variable, don't create a local config variable. Just delete this line:

config := Config{}

Note:

The above line is a short variable declaration which creates a new variable.

You most likely just wanted to assign an empty Config{} struct value to config, but for that you have to use an assignment:

config = Config{}

But this is not needed in this case, as the global variable declaration:

var config Config

will initialize the config global variable to its zero value, which in case of structs is a struct value where all its fields are also initialized to the zero values of their types.

icza
  • 389,944
  • 63
  • 907
  • 827