英文:
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 "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
得分: 2
你不需要这样做。Go Tour程序将会向你的程序传递Pic测试值。你的问题出在你的代码上:panic: runtime error: index out of range。[][]uint8{}和[]uint8{}分别分配了零个y和零个x切片元素。使用make来分配你的y和x切片。例如,
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 "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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论