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

Cas*_*eyB 4 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
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

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)
}
Run Code Online (Sandbox Code Playgroud)

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

pet*_*rSO 6

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

a [低:高]

构造子字符串或切片.索引表达式低和高选择哪些元素出现在结果中.结果索引从0开始,长度等于高 - 低.

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

索引

表单的主要表达方式

斧头]

表示由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
Run Code Online (Sandbox Code Playgroud)

制作切片,地图和频道

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
Run Code Online (Sandbox Code Playgroud)

y必须是整数值且0 <= y <len(pixel [] uint8).x必须是整数值且0 <= x <len(pixel [] [] 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)
}
Run Code Online (Sandbox Code Playgroud)