gpt4 book ai didi

Golang panic : runtime error: index out of range only happens when run outside debugger

转载 作者:IT王子 更新时间:2023-10-29 01:19:31 31 4
gpt4 key购买 nike

我有以下代码用于在给定 slice 中查找总和为给定总数的两个整数:

type Store_object struct {
C int
I int
Prices []int
}
//..other unrelated functions...

func FindItemPairs(scenarios []Store_object) ([]string, error) {
var results []string
for scIndex := 0; scIndex < len(scenarios); scIndex++ {
scenario := scenarios[scIndex]
for prIndex := 0; prIndex < len(scenario.Prices); prIndex++ { //<--!sc
firstItem := scenario.Prices[prIndex]
if firstItem >= scenario.C {
continue
}
for cmpIndex := prIndex + 1; cmpIndex < len(scenario.Prices); cmpIndex++ {
secondItem := scenario.Prices[cmpIndex]

switch {
case secondItem >= scenario.C:
continue
case firstItem+secondItem == scenario.C:
result := "Case #" + strconv.Itoa(scIndex+1) +
" " + strconv.Itoa(firstItem) + " " +
strconv.Itoa(secondItem)
results = append(results, result)
}
}
}
}
return results, nil
}

但是,当我尝试运行我的代码来查找项目对时,出现以下错误:

panic: runtime error: index out of range

goroutine 1 [running]:
<store_credit>.FindItemPairs(0x208208000, 0x1e, 0x20, 0x0, 0x0, 0x0, 0x0, 0x0)
<store_credit_location>.go:76 +0x4ac
main.main()
<main_dir>/test_sc.go:16 +0x24d
exit status 2

(相关行用上面的 <--!sc 和下面的 <--!main 标注)

为了尝试调试,我使用了以下项目https://github.com/mailgun/godebug进行测试,发现我的代码执行没有问题。

我目前不知道如何访问超出范围的值,但不知道我将如何进一步调试...

如有任何相关指导,我们将不胜感激!

有关更多上下文,这是我正在尝试实现的代码堵塞:https://code.google.com/codejam/contest/351101/dashboard#s=p0

编辑:有关更多上下文,这是我正在运行的调用此函数的主文件:

func main() {
cases, err := store_credit.ReadLines("A-small-practice.in")
if err != nil {
fmt.Println(err)
}

fmt.Println(cases)

results, err := store_credit.FindItemPairs(cases) //<--!main
if err != nil {
fmt.Println(err)
}

for i := 0; i < len(results); i++ {
fmt.Println(results[i])
}
}

ReadLines 工作正常,没有任何问题。

最佳答案

看来您可能在某处发生了数据竞争。尝试使用 -race 标志运行它。

go run -race myfile.go

关于Golang panic : runtime error: index out of range only happens when run outside debugger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31691351/

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