How to assert map contains key?

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

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).

huangapple
  • 本文由 发表于 2022年10月6日 02:05:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/73964527.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定