Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assert map contains key?

I have an map object in golang of the type: *map[string]interface{} , how can I assert it contain certain keys? Here is what I have:

type respObj struct {
    ExternalIds *map[string]interface{} `json:"externalIds,omitempty"`
}
myObj := getRespObj()
out, _ := json.Marshal(myObj)
fmt.Println("Response: ", string(out))
// {"externalIds":{"payroll":"bigmoney","serial":"GA3MXX4VV7","vin":"1G1YY3388L5112656"}}
assert.NotNil(t, myObj.ExternalIds)
assert.Contains(t, &myObj.ExternalIds, "payroll")
assert.Contains(t, &myObj.ExternalIds, "serial")
assert.Contains(t, &myObj.ExternalIds, "vin")

Currently throwing error:

Error:          "%!s(**map[string]interface {}=0xc0079bf920)" could not be applied builtin len()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should pass a map to assert.Contains().

myObj.ExternalIds is a pointer to a map, so &myObj.ExternalIds will be a pointer to a pointer to a map.

Instead of taking its address, dereference the pointer:

assert.Contains(t, *myObj.ExternalIds, "payroll")
assert.Contains(t, *myObj.ExternalIds, "serial")
assert.Contains(t, *myObj.ExternalIds, "vin")

Note that maps are pointers under the hood. Its rare that you need a pointer to a map, passing maps have pointer semantics, and it’s efficient (only a pointer is passed under the hood).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading