英文:
How to assert map contains key?
问题
我在golang中有一个类型为*map[string]interface{}
的地图对象,我如何断言它包含某些键?这是我的代码:
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")
目前抛出错误:
Error: "%!s(**map[string]interface {}=0xc0079bf920)" could not be applied builtin len()
请注意,我只翻译了代码部分,其他内容不做翻译。
英文:
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()
答案1
得分: 0
你应该将一个map传递给assert.Contains()
。
myObj.ExternalIds
是一个指向map的指针,所以&myObj.ExternalIds
将是一个指向指针的指针。
不要取它的地址,解引用指针:
assert.Contains(t, *myObj.ExternalIds, "payroll")
assert.Contains(t, *myObj.ExternalIds, "serial")
assert.Contains(t, *myObj.ExternalIds, "vin")
请注意,map在底层是指针。很少需要一个指向map的指针,传递map具有指针语义,而且效率高(在底层只传递一个指针)。
英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论