Go tour #18. How do I pass in integers to Pic?

huangapple go评论97阅读模式
英文:

Go tour #18. How do I pass in integers to Pic?

问题

以下是代码的中文翻译:

package main

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

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

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

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

这段代码出现了索引超出范围的错误。我尝试将main函数修改为pic.Show(Pic(500, 500)),但这样会将参数从函数改为返回类型,导致编译失败。如果pic.Show期望一个函数作为参数,我该如何传入整数呢?

英文:

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 &quot;golang.org/x/tour/pic&quot;

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

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

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

答案1

得分: 2

你不需要这样做。Go Tour程序将会向你的程序传递Pic测试值。你的问题出在你的代码上:panic: runtime error: index out of range[][]uint8{}[]uint8{}分别分配了零个y和零个x切片元素。使用make来分配你的yx切片。例如,

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

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

英文:

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 &quot;golang.org/x/tour/pic&quot;

func Pic(dx, dy int) [][]uint8 {
	pixels := make([][]uint8, dy)
	for y := 0; y &lt; dy; y++ {
		pixels[y] = make([]uint8, dx)
		for x := 0; x &lt; 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

huangapple
  • 本文由 发表于 2017年5月29日 01:20:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/44230022.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定