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

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

Check if a map is initialised in Golang

问题

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

结构体:

  1. type Config struct {
  2. SolrHost string
  3. SolrPort int
  4. SolrCore string
  5. Servers map[string][]int
  6. }

要解码的 JSON 数据:

  1. {
  2. "solrHost": "localhost",
  3. "solrPort": 8380,
  4. "solrCore": "testcore",
  5. }

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

当前的代码:

  1. func decodeJson(input string, output *Config) error {
  2. if len(input) == 0 {
  3. return fmt.Errorf("empty string")
  4. }
  5. decoder := json.NewDecoder(strings.NewReader(input))
  6. err := decoder.Decode(output)
  7. if err != nil {
  8. if err != io.EOF {
  9. return err
  10. }
  11. }
  12. // if output.Server.isNotInitialized...
  13. return nil
  14. }

我可以使用 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:

  1. type Config struct {
  2. SolrHost string
  3. SolrPort int
  4. SolrCore string
  5. Servers map[string][]int
  6. }

JSON to decode:

  1. {
  2. "solrHost": "localhost",
  3. "solrPort": 8380,
  4. "solrCore": "testcore",
  5. }

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:

  1. func decodeJson(input string, output *Config) error {
  2. if len(input) == 0 {
  3. return fmt.Errorf("empty string")
  4. }
  5. decoder := json.NewDecoder(strings.NewReader(input))
  6. err := decoder.Decode(output)
  7. if err != nil {
  8. if err != io.EOF {
  9. return err
  10. }
  11. }
  12. // if output.Server.isNotInitialized...
  13. return nil
  14. }

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

答案1

得分: 20

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

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

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

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

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

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

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

  1. 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:

确定