检查在Golang中是否初始化了一个映射。

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

Check if a map is initialised in Golang

问题

我正在解码一些 JSON 数据到一个结构体中,并且我想处理一个特定字段未提供的情况。

结构体:

type Config struct {
    SolrHost string
    SolrPort int
    SolrCore string
    Servers  map[string][]int
}

要解码的 JSON 数据:

{
  "solrHost": "localhost",
  "solrPort": 8380,
  "solrCore": "testcore",
}

在解码 JSON 的方法中,我想检查 map[string][]int 是否已初始化,如果没有,则进行初始化。

当前的代码:

func decodeJson(input string, output *Config) error {
    if len(input) == 0 {
        return fmt.Errorf("empty string")
    }
    decoder := json.NewDecoder(strings.NewReader(input))
    err := decoder.Decode(output)
    if err != nil {
        if err != io.EOF {
            return err
        }
    }

    // if output.Server.isNotInitialized...

    return nil
}

我可以使用 recover() 吗?这是实现我的任务的"最好"方式吗?

英文:

I'm decoding some JSON into a struct, and I'd like to handle the case where a particular field is not provided.

Struct:

type Config struct {
    SolrHost string
    SolrPort int
    SolrCore string
    Servers  map[string][]int
}

JSON to decode:

{
  "solrHost": "localhost",
  "solrPort": 8380,
  "solrCore": "testcore",
}

In the method that decodes the JSON, I'd like to check if the map[string][]int has been initialised, and if not, do so.

Current code:

func decodeJson(input string, output *Config) error {
    if len(input) == 0 {
        return fmt.Errorf("empty string")
    }
    decoder := json.NewDecoder(strings.NewReader(input))
    err := decoder.Decode(output)
    if err != nil {
        if err != io.EOF {
            return err
        }
    }

    // if output.Server.isNotInitialized...

    return nil
}

Could I make use of recover()? Is that the "nicest" way to achieve my task?

答案1

得分: 20

任何映射的零值都是nil,所以只需检查它是否为nil

if output.Servers == nil { /* ... */ }

或者,你也可以检查它的长度。这也处理了空映射的情况:

if len(output.Servers) == 0 { /* ... */ }
英文:

The zero value of any map is nil, so just check against it:

if output.Servers == nil { /* ... */ }

Alternatively, you can also check its length. This also handles the case of empty map:

if len(output.Servers) == 0 { /* ... */ }

huangapple
  • 本文由 发表于 2015年7月10日 19:07:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/31339249.html
匿名

发表评论

匿名网友

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

确定