check if a generic map key exists within a typed struct

  Kiến thức lập trình

I have an endpoint that is doing a partial update. I want to make sure that the incoming body doesn’t contain invalid keys

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

incomming data:

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

what I would like to do is this:

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

The issue is that MyStruct isn’t generic and I get the error:

invalid operation: MyStruct[key] (MyStruct is not a generic type)

LEAVE A COMMENT