简体   繁体   中英

Check if a map is initialised in Golang

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?

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 { /* ... */ }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM