【问题标题】:Tour of Go exercise #18: Slices, index out of rangeGo 练习之旅 #18:切片、索引超出范围
【发布时间】:2012-07-20 18:31:02
【问题描述】:

我正在完成围棋之旅中的练习,但遇到了一个我无法弄清楚的问题。

我正在做Exercise: Slices,我收到了这个错误:

256 x 256

panic: runtime error: index out of range [0] with length 0

goroutine 1 [running]:
main.Pic(0x100, 0x100)
    /tmp/sandbox1628012103/prog.go:14 +0xcf
golang.org/x/tour/pic.Show(0xc0000001a0)
    /tmp/gopath962180923/pkg/mod/golang.org/x/tour@v0.0.0-20201207214521-004403599411/pic/pic.go:32 +0x28
main.main()
    /tmp/sandbox1628012103/prog.go:25 +0x25

这是我的代码:

package main

import (
    "fmt"
    "golang.org/x/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)
}

【问题讨论】:

标签: go


【解决方案1】:

Slices

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

a[低:高]

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

对于数组或字符串,索引 low 和 high 必须满足 0

Indexes

表单的主要表达方式

a[x]

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

对于 A 或 *A 类型的 a,其中 A 是数组类型,或对于 S 类型的 a 其中 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

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

【讨论】:

  • 所以 make([]uint8, dx) 制作了一个包含 dx 零的切片?如果是这种情况,那与容量有何不同?我的意思是如果我 make([]uint8, 0, dx) 不会创建一个可以容纳 dx uint8s 但我们目前为空的切片吗?
  • 看我的回答。 make([]uint8, dx) 等价于 make([]uint8, dx, dx) 即 len()= dx 和 cap() = dx,与 make([]uint8, 0, dx) 不同,即 len() = 0 和 cap() = dx。在这两种情况下,底层数组都是 cap() = dx 零值元素。索引必须为 0
【解决方案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)
 }

【讨论】:

  • 代码只回答,没有任何描述或解释做了什么改变或为什么不是很有帮助。
猜你喜欢
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 2019-11-05
  • 2023-03-29
  • 1970-01-01
  • 2023-03-30
  • 1970-01-01
  • 2015-10-30
相关资源
最近更新 更多