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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程