dougan1330 2017-05-28 17:20
浏览 35
已采纳

前往游览#18。 如何将整数传递给Pic?

The following code errors with index out of range. I tried modifying main to pic.Show(Pic(500, 500)) but that changes the argument from function to the return type and it fails to compile. How do I pass in integers if the pic.Show is expecting a function as an argument.

package main

import "golang.org/x/tour/pic"

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

    mypic := [][]uint8{}
    for y := 0; y < dy; y++ {
        mypic[y] = []uint8{}
        for x := 0; x < dx; x++ {
            mypic[y][x] = uint8((x + y) / 2)
        }
    }
    return mypic
}

func main() {
    pic.Show(Pic)
}
  • 写回答

1条回答 默认 最新

  • dpp66953 2017-05-28 17:34
    关注

    You don't. The Go Tour program will pass Pic test values to your program. Your problem is in your code: panic: runtime error: index out of range. [][]uint8{} and []uint8{} allocate zero y and zero x slice elements. Use make to allocate your y and x slices. For example,

    package main
    
    import "golang.org/x/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) / 2)
            }
        }
        return pixels
    }
    
    func main() {
        pic.Show(Pic)
    }
    

    Reference: Making slices, maps and channels, The Go Programming Language Specification

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画