gpt4 book ai didi

go - 我不确定为什么索引超出范围错误

转载 作者:行者123 更新时间:2023-12-01 22:38:56 25 4
gpt4 key购买 nike

我收到错误消息:

紧急:运行时错误:索引超出范围

goroutine 7 [运行中]:
main.start(0xc0000540e0、0x8、0xc0000542a0、0x63、0x1、0xc00249a0c0)

当我尝试在某些日志(而不是全部日志)上运行程序时。

导致此错误的代码似乎是:

end, _ := time.Parse("15:04:05", lines[len(lines)-1].Timestamp)
start, _ := time.Parse("15:04:05", lines[0].Timestamp)
midnight, _ := time.Parse("15:04:05", "00:00:00")
duration := end.Sub(start).Seconds()
if start.Hour() > end.Hour() {
toMidnight := 24*3600 - start.Sub(midnight).Seconds()
timeDuration = toMidnight + end.Sub(midnight).Seconds()
}

最佳答案

首先,切勿遗漏错误!

要回答您的问题:如果lines为空(len(lines) == 0),则len(lines)-1将是-1,这可能会触发您的错误。

同样,如果lines为空,则lines[0]也超出范围,但前一行会出现紧急情况,因此您不会在此处结束。

我想知道lines是否为空,应该跳过整个代码(没有要分析的内容),因此首先检查一下。例如:

if len(lines) == 0 {
return
}

// There are lines, it's safe to index it with 0 and len(lines)-1

...

关于go - 我不确定为什么索引超出范围错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58310733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com