加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Golang恐慌:运行时错误:索引超出范围仅在调试器外部运行时发生

发布时间:2020-12-16 19:03:23 所属栏目:大数据 来源:网络整理
导读:我有以下代码用于查找给定切片中给定总和的两个整数: 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; s
我有以下代码用于查找给定切片中给定总和的两个整数:
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)
<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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读