douwen9343 2018-06-11 14:54
浏览 35
已采纳

无法访问函数内部的全局变量

This question already has an answer here:

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

</div>
  • 写回答

1条回答 默认 最新

  • dragon8002 2018-06-11 14:55
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog