Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 388
shearn89 Avatar asked Jul 10 '15 11:07

shearn89


People also ask

How do you initialize a map in Golang?

Initializing map using map literals: Map literal is the easiest way to initialize a map with data just simply separate the key-value pair with a colon and the last trailing colon is necessary if you do not use, then the compiler will give an error.

How do I know if a map is nil Golang?

You can use len : if len(m) == 0 { .... }

How do you initialize an empty map in Golang?

Go by Example: Maps To create an empty map, use the builtin make : make(map[key-type]val-type) . Set key/value pairs using typical name[key] = val syntax. Printing a map with e.g. fmt. Println will show all of its key/value pairs.

How do you check if a key is in a map Golang?

Check if Key is Present in Map in Golang To check if specific key is present in a given map in Go programming, access the value for the key in map using map[key] expression. This expression returns the value if present, and a boolean value representing if the key is present or not.


Video Answer


1 Answers

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 { /* ... */ }
like image 101
Ainar-G Avatar answered Sep 29 '22 09:09

Ainar-G