title: Storing Sql result sets in a nested struct and omit if empty
body: <p>I am trying to store SQL query dataset in a struct and display in JSON. I have almost done it. Now the problem is if the result set of nested structs is empty then I would not like to display it. </p>
  
  <p>Same problem <a href="https://stackoverflow.com/questions/33447334/golang-json-marshal-how-to-omit-empty-nested-struct">specified here</a> but using a pointer ends in a panic when scanning may be because I am using <code>&amp;user.Profile.Firstname</code></p>
  
  <blockquote>
    <p>2015/11/01 16:42:16 Panic recovery -> runtime error: invalid memory address or nil pointer dereference</p>
  </blockquote>
  
  <p>If I remove the pointer then everything works fine just the empty field remains. I am confused how to achieve this.</p>
  
  <pre><code>package main
  
  import (
      "database/sql"
      "github.com/gin-gonic/gin"
      _ "github.com/go-sql-driver/mysql"
      "log"
  )
  
  type User struct {
      Id       int64
      Username string
      Email    string
      Profile  Profile `json:",omitempty"`
  }
  
  type Profile struct {
      Id        int64  `json:",omitempty"`
      UserId    int64  `json:",omitempty"`
      Firstname *string `json:",omitempty"`
      Lastname  *string `json:",omitempty"`
  }
  
  var DB *sql.DB
  
  func checkErr(err error, msg string) {
      if err != nil {
          log.Fatal(msg, err)
      }
  }
  
  func main() {
      DB, _ = sql.Open("mysql", "username:secrect@/database")
      defer DB.Close()
  
      r := gin.Default()
      v1 := r.Group("api/v1/")
      {
          v1.GET("users", GetUsers)
      }
      r.Run(":8080")
  }
  
  
  func GetUsers(c *gin.Context) {
      stmt, err := DB.Query("Select users.id, username , email , firstname , lastname from users left join profiles on users.id = profiles.user_id ")
      if err != nil {
          panic(err.Error())
      }
      defer stmt.Close()
  
      users := []User{}
  
      for stmt.Next() {
          var user User
          err := stmt.Scan(&amp;user.Id, &amp;user.Username, &amp;user.Email, &amp;user.Profile.Firstname, &amp;user.Profile.Lastname)
          if err != nil {
              panic(err.Error())
          }
  
          users = append(users, user)
      }
  
      c.JSON(200, &amp;users)
  }
  </code></pre>
  
  <p><strong>Output:</strong></p>
  
  <pre><code>{
    "Id": 1,
    "Username": "test1",
    "Email": "test1@example.com",
    "Profile": {
      "Firstname": "John",
      "Lastname": "Doe"
    }
  },
  {
    "Id": 2,
    "Username": "test2",
    "Email": "test2@example.com",
    "Profile": {
    }
  },
  </code></pre>