title: What is causing this segfault in Go?
body: <p><strong>Background:</strong> Because Go's inbuilt JSON marshaller doesn't check for zero values when given the <code>omitempty</code> flag, we're trying using <code>*time.Time</code> rather than <code>time.Time</code> in structs that need to be marshalled cleanly to JSON. The problem with this is obviously we need to be very careful to always check it is not nil when using it. One thing we did notice was in a function that sets a creation time on the encompassing struct, when we checked the JSON in the database all of the times were exactly the same, down to the nanosecond.</p>
  
  <p>To check whether this was something to do with the pointer or just because the system was performing very well, I made <a href="https://play.golang.org/p/Fq_3984pZ4" rel="noreferrer">this test</a>:</p>
  
  <pre><code>package main
  
  import (
      "fmt"
      "time"
  )
  
  type Timekeeper struct {
      myTime *time.Time
  }
  
  func main() {
  
      t := make([]Timekeeper, 100)
      var now time.Time
      for _, v := range t {
          now = time.Now()
          v.myTime = &amp;now
          time.Sleep(1 * time.Second)
      }
  
      for i, times := range t {
          fmt.Printf("Timekeeper %s time: %s.", i, times.myTime.Format(time.RFC3339Nano))
      }
  
  }
  </code></pre>
  
  <p>but it keeps producing this panic:</p>
  
  <pre><code>panic: runtime error: invalid memory address or nil pointer dereference
  [signal SIGSEGV: segmentation violation code=0xffffffff addr=0x0 pc=0x20314]
  
  goroutine 1 [running]:
  panic(0x112c00, 0x1040a038)
      /usr/local/go/src/runtime/panic.go:500 +0x720
  main.main()
      /tmp/sandbox675251439/main.go:23 +0x314
  
  Program exited.
  </code></pre>
  
  <p>I'm assuming this is <em>something</em> to do with the pointer being constantly reassigned to, but I've got a mental block going on and I can't figure out exactly what the issue is. Can someone please explain what is happening here?</p>