title: How to check if a json matches a struct / struct fields
body: <p>Is there an easy way to check if each field of myStruct was mapped by using json.Unmarshal(jsonData, &amp;myStruct).</p>
  
  <p>The only way I could image is to define each field of a struct as pointer, otherwise you will always get back an initialized struct.
  So every jsonString that is an object (even an empty one {}) will return an initialized struct and you cannot tell if the json represented your struct.</p>
  
  <p>The only solution I could think of is quite uncomfortable:</p>
  
  <pre><code>package main
  
  import (
      "encoding/json"
      "fmt"
  )
  
  type Person struct {
      Name *string `json:name`
      Age  *int    `json:age`
      Male *bool   `json:male`
  }
  
  func main() {
      var p *Person
      err := json.Unmarshal([]byte("{}"), &amp;p)
      // handle parse error
      if err != nil {
          return
      }
  
      // handle json did not match error
      if p.Name == nil || p.Age == nil || p.Male == nil {
          return
      }
  
      // now use the fields with dereferencing and hope you did not forget a nil check
      fmt.Println("Hello " + *p.Name)
  }
  </code></pre>
  
  <p>Maybe one could use a library like <a href="https://github.com/asaskevich/govalidator" rel="noreferrer">govalidator</a> and use SetFieldsRequiredByDefault. But then you still have to execute the validation and still you are left with the whole pointer dereferencing for value retrieval and the risk of nil pointer.</p>
  
  <p>What I would like is a function that returns my unmarshaled json as a struct or an error if the fields did not match. The only thing the golang json library offers is an option to fail on unknown fields but not to fail on missing fields.</p>
  
  <p>Any idea?</p>