是什么导致Go中出现此段错误?

Background: Because Go's inbuilt JSON marshaller doesn't check for zero values when given the omitempty flag, we're trying using *time.Time rather than time.Time 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.

To check whether this was something to do with the pointer or just because the system was performing very well, I made this test:

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 = &now
        time.Sleep(1 * time.Second)
    }

    for i, times := range t {
        fmt.Printf("Timekeeper %s time: %s.", i, times.myTime.Format(time.RFC3339Nano))
    }

}

but it keeps producing this panic:

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.

I'm assuming this is something 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?

查看全部
duanchuo7741
duanchuo7741
2016/12/21 11:04
  • segmentation-fault
  • pointers
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复