Golang:类型[type]不是一个表达式;JSON配置解析

huangapple go评论91阅读模式
英文:

Golang: Type [type] is not an expression; json config parsing

问题

我正在尝试编写一段代码来从一个JSON文件中获取配置信息。当我尝试构建时,出现了以下错误:

类型 ConfigVars 不是一个表达式

以下是我正在尝试使用的配置文件和程序代码。到目前为止,我找到的每个示例都类似于下面的代码。你有什么建议,我做错了什么吗?

-- 配置文件
{"beaconUrl":"http://test.com/?id=1"}

-- 程序代码
package main

import (
    "encoding/json"
    "fmt"
    "os"
)


type ConfigVars struct {
    BeaconUrl   string
}


func main() {
    configFile, err := os.Open("config.json")
    defer configFile.Close()
    if err != nil {
        fmt.Println("打开配置文件时出错", err.Error())
    }

    jsonParser := json.NewDecoder(configFile)
    if err = jsonParser.Decode(&ConfigVars); err != nil {
        fmt.Println("解析配置文件时出错", err.Error())
    }
}
英文:

I'm trying to work out a bit of code to pull in config from a JSON file.
When I attempt to build, I get this error

type ConfigVars is not an expression

Below is the config and program code I'm trying to work with. Every example I've found so far is similar to the below code. Any suggestion of what I'm doing incorrectly?

-- Config File
{"beaconUrl":"http://test.com/?id=1"}

-- Program Code
package main

import (
    "encoding/json"
    "fmt"
    "os"
)


type ConfigVars struct {
    BeaconUrl   string
}


func main() {
    configFile, err := os.Open("config.json")
    defer configFile.Close()
    if err != nil {
        fmt.Println("Opening config file", err.Error())
    }

    jsonParser := json.NewDecoder(configFile)
    if err = jsonParser.Decode(&ConfigVars); err != nil {
        fmt.Println("Parsing config file", err.Error())
    }
}

答案1

得分: 8

你在那里做的是尝试传递一个指向ConfigVars类型的指针(显然这并没有实际意义)。你想要做的是创建一个类型为ConfigVars的变量,并传递该变量的指针:

var cfg ConfigVars
err = jsonParser.Decode(&cfg)
...
英文:

What you're doing there is trying to pass a pointer to the ConfigVars type (which obviously doesn't really mean anything). What you want to do is make a variable whose type is ConfigVars and pass a pointer to that instead:

var cfg ConfigVars
err = jsonParser.Decode(&cfg)
...

答案2

得分: 0

对于其他遇到这个问题的人来说,你可能会发现在使用:=运算符进行赋值时,你忘记了初始化变量,就像GoLang教程的最后一点所描述的那样。

var cfg ConfigVars
err := jsonParser.Decode(&cfg)
英文:

For others who come onto this problem, you may find that you've forgotten to initialize the variable during assignment using the := operator, as described in Point 3 at the end of this GoLang tutorial.

var cfg ConfigVars
err := jsonParser.Decode(&cfg)

huangapple
  • 本文由 发表于 2016年3月4日 11:31:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/35787463.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定