Go Tour,运动:切片指数超出范围

时间:2012-07-20 18:31:03

标签: go

我正在参加Go语言巡回演唱会的练习,我遇到了一些我无法弄清楚的障碍。我正在做Exercise: Slices,我收到了这个错误:

256 x 256

panic: runtime error: index out of range

goroutine 1 [running]:
main.Pic(0x10000000100, 0x3, 0x417062, 0x4abf70)
    /tmpfs/gosandbox-08a27793_4ffc9f4a_3b917355_ef23793d_c15d58cc/prog.go:9 +0xa0
tour/pic.Show(0x400c00, 0x40caa2)
    go/src/pkg/tour/pic/pic.go:20 +0x2d
main.main()
    /tmpfs/gosandbox-08a27793_4ffc9f4a_3b917355_ef23793d_c15d58cc/prog.go:20 +0x25

这是我的代码:

package main

import "tour/pic"

func Pic(dx, dy int) [][]uint8 {
    fmt.Printf("%d x %d\n\n", dx, dy)

pixels := make([][]uint8, 0, dy)

for y := 0; y < dy; y++ {
    pixels[y] = make([]uint8, 0, dx)

    for x := 0; x < dx; x++ {
        pixels[y][x] = uint8(x*y)
    }
}

return pixels
}

func main() {
    pic.Show(Pic)
}

对于我的生活,我找不到问题!

2 个答案:

答案 0 :(得分:6)

  

Slices

     

对于字符串,数组,指向数组的指针或切片a,主要的   表达

     

a [low:high]

     

构造子字符串或切片。索引表达式低和高   选择结果中显示的元素。结果有索引   从0开始,长度等于高 - 低。

     

对于数组或字符串,索引低和高必须满足0 <=低   &lt; = high&lt; = length;对于切片,上限是容量而不是   而不是长度。

     

Indexes

     

表单的主要表达式

     

一[X]

     

表示由x索引的数组,切片,字符串或映射的元素。   值x分别称为索引或映射键。该   以下规则适用:

     

对于类型A或* A,其中A是数组类型,或类型为S   其中S是切片类型:

x must be an integer value and 0 <= x < len(a)

a[x] is the array element at index x and the type of a[x] is
the element type of A

if a is nil or if the index x is out of range, a run-time panic occurs
     

Making slices, maps and channels

make(T, n)       slice      slice of type T with length n and capacity n
make(T, n, m)    slice      slice of type T with length n and capacity m

y必须是整数值且0 <= y <1。 LEN(像素[] UINT8)。 x必须是整数值并且0 <= x <1。 LEN(像素[] [] UINT8)。例如,

package main

import "tour/pic"

func Pic(dx, dy int) [][]uint8 {
    pixels := make([][]uint8, dy)
    for y := 0; y < dy; y++ {
        pixels[y] = make([]uint8, dx)
        for x := 0; x < dx; x++ {
            pixels[y][x] = uint8(x * y)
        }
    }
    return pixels
}

func main() {
    pic.Show(Pic)
}

答案 1 :(得分:-2)

package main

import "tour/pic"

func Pic(dx, dy int) [][]uint8 {
fmt.Printf("%d x %d\n\n", dx, dy)

     pixels := make([][]uint8, 0, dy)

       for y := 0; y < dy; y++ {
    //    pixels[y] = make([]uint8, 0, dx)

for x := 0; x < dx; x++ {
 // append can skip make statement   
 pixels[y] = append(pixels[y],uint8(x*y)) 

     }
}

 return pixels
}

 func main() {
    pic.Show(Pic)
 }