检查类型化结构中是否存在通用映射键

问题描述 投票:0回答:1

我有一个正在执行部分更新的端点。我想确保传入的正文不包含无效的密钥

type MyStruct struct {
    Code string `json:"code"`
    Name string `json:"name"`
}

传入数据:

{
  "code": "asdfa",
  "name": "foo",
  "bar": true
}

我想做的是这样的:

    for key, _ := range incommingData {
        if _, ok := MyStruct[key]; !ok {
            fmt.Printf("incommingData contains a key: %s not available in the MyStruct struct", key)
        }
    }

问题是

MyStruct
不是通用的,我收到错误:

无效操作:MyStruct[key](MyStruct 不是泛型类型)

go
1个回答
0
投票

@Brits 的答案对我有帮助,使用 DisallowUnknownFields

© www.soinside.com 2019 - 2024. All rights reserved.