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 删除虚拟显示器驱动 删除所有 Xorg 配置文件 删除显示器缓存文件 重启系统 可是依旧无法退出虚拟显示器
  • ¥15 vscode程序一直报同样的错,如何解决?
  • ¥15 关于使用unity中遇到的问题
  • ¥15 开放世界如何写线性关卡的用例(类似原神)
  • ¥15 关于并联谐振电磁感应加热
  • ¥60 请查询全国几个煤炭大省近十年的煤炭铁路及公路的货物周转量
  • ¥15 请帮我看看我这道c语言题到底漏了哪种情况吧!
  • ¥66 如何制作支付宝扫码跳转到发红包界面
  • ¥15 pnpm 下载element-plus
  • ¥15 解决编写PyDracula时遇到的问题