dongse7261 2016-03-28 11:03
浏览 99

Golang索引超出范围

I'm trying to make a simply example of Golang. The example it's in te 36º page of the tour of golang. This is my code:

package main

import "code.google.com/p/go-tour/pic"
import "fmt"

func Pic(dx, dy int) [][]uint8 {
    dx8 := uint8(dx)

    s1 := make ([][] uint8, dy)
    fmt.Printf("%d
", len(s1), cap(s1))

    for i := range s1{
        fmt.Printf("%d
",i)
        for j := range s1 {
            fmt.Printf("%d
",j)
            s1[i][j] = dx8    
        }
    }

    return s1
}

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

And the error I got:

    256
%!(EXTRA int=256)0
0
panic: runtime error: index out of range

goroutine 1 [running]:
panic(0x18b820, 0x1040a010)
    /usr/local/go/src/runtime/panic.go:464 +0x700
main.Pic(0x100, 0x100, 0x0, 0x0, 0x0, 0x0)
    /tmp/sandbox716191956/main.go:17 +0x4e0
code.google.com/p/go-tour/pic.Show(0x1d7988, 0x104000e0)
    /go/src/code.google.com/p/go-tour/pic/pic.go:20 +0x60
main.main()
    /tmp/sandbox716191956/main.go:26 +0x20

Program exited.

I only want to return a bidimensial slice which Show function uses.

  • 写回答

2条回答 默认 最新

  • dongyong6428 2016-03-28 11:41
    关注

    You need to make the slices for both dimensions, dy and dx, of the picture. For example,

    package main
    
    import "golang.org/x/tour/pic"
    
    func Pic(dx, dy int) [][]uint8 {
        p := make([][]uint8, dy)
        for i := range p {
            p[i] = make([]uint8, dx)
            for j := range p[i] {
                p[i][j] = uint8(i * j)
            }
        }
        return p
    }
    
    func main() {
        pic.Show(Pic)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向