duanchuo7741 2016-12-21 11:04
浏览 212
已采纳

是什么导致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?

  • 写回答

1条回答 默认 最新

  • drl6054 2016-12-21 11:12
    关注

    In your loop you copy every Timekeeper value. Do this instead:

    for i := range t {
        now = time.Now()
        t[i].myTime = &now
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料