doushuo8677 2016-06-06 23:15
浏览 43
已采纳

遍历2D切片

I am taking the "Tour of Go", and had a question regarding the Exercise: Slices example. Currently I can create the picture by iterating over each index using the the [] operator, just like you could in C.

func Pic(dx, dy int) [][]uint8 {
    pic := make([][]uint8, dy)
    for i := range pic {
        pic[i] = make([]uint8, dx)
        for j := range pic[i] {
            pic[i][j] = uint8(1)
        }
    }
    return pic
} 

However, when I try to do something like below, I get an panic: runtime error: index out of range error. I tried adding print statements and calling Pic(3, 3), which printed out a 3x3 array just fine.

func Pic(dx, dy int) [][]uint8 {
    pic := make([][]uint8, dy)
    for _, y := range pic {
        y = make([]uint8, dx)
        for _, x := range y {
            x = uint8(1)
            _ = x // x has to be used
            //fmt.Print("1")
        }
        //fmt.Print("
")
    }
    return pic
}

Any thoughts on what I am doing wrong?

  • 写回答

2条回答 默认 最新

  • douxu5233 2016-06-06 23:27
    关注

    The main problem is your attempt to do assignment. Check my example using your code; https://play.golang.org/p/lwoe79jQ70

    What you actually get out of the latter implementation is a 3x0 array, all of the inner arrays are empty. The reason for this is because you're using the range variable for assignment which doesn't work. If the current index is 0, y != pic[0], pic[0] is assigned to y however, y is temporary storage, it typically is the same address and is over written on each iteration. So after the latter example executes, all your x direction arrays are empty, indexing into one causes a panic.

    Basically you should just be using your first implementation because it works fine and is the way you would typically do this. But the take away is, when you do a, b := range Something b != Something[a], it is it's on instance, it goes out of scope at the bottom of the loop and assigning to it will not cause a state change to the collection Something, instead you must assign to Something[a] if you want to modify Something[a].

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题