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条)

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?