dpl3350 2016-08-16 09:24
浏览 74
已采纳

在Golang中分别访问数组元素

I know this is very basic but i want to know how to access elements individually,the values of Sourceposition and currentarray keep changing, this operation is apart of recursive function.

For example:

 var Sourceposition int

var currentarray [8]int

for j:=0;j<len(currentarray);j++
{
  if currentarray[j]==0{
  Sourceposition = currentarray[j+1]}
fmt.Pritnln(Sourceposition)
}

//random statements

this gives me a error index out of range, Can someone help me , how to this calculation.

  • 写回答

1条回答 默认 最新

  • donglu1973 2016-08-16 10:07
    关注

    On your last iteration (when j == len(currentarray) - 1 which is 7) you're accessing currentarray[7] and then if that equals zero trying to access currentarray[8] which is out of range for [8]int.

    The fix depends on the intended behaviour, it might be that you need to fix your loop invariant to be j < len(currentarray) - 1, or, if you want to treat your array in a circular way, you may want to do Sourceposition = currentarray[(j + 1) % len(currentarray)].

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么