我正在学习 golang 并试图完成 go 之旅。我被困在切片练习上。在此处复制粘贴问题和我的解决方案。有人可以批评它并告诉我我在这里做错了什么吗?
问题:
Implement Pic. It should return a slice of length dy, each element of which is a slice of dx 8-bit
unsigned integers. When you run the program, it will display your picture,
interpreting the integers as grayscale (well, bluescale) values.
The choice of image is up to you. Interesting functions include (x+y)/2, x*y, and x^y.
(You need to use a loop to allocate each []uint8 inside the [][]uint8.)
(Use uint8(intValue) to convert between types.)
我的解决方案:
package main
import "golang.org/x/tour/pic"
func Pic(dx, dy int) [][]uint8 {
ans := make([][]uint8, dy)
for i:=0; i< dy; i++ {
slice := make([]uint8, dx)
for j := 0; j<dx;j++{
slice = append(slice, uint8((i+j)/2))
}
ans = append(ans,slice)
}
return ans
}
func main() {
pic.Show(Pic)
}
运行时出现错误:
恐慌:运行时错误:索引超出范围 [0],长度为 0
我不确定我在这里做错了什么。另外,为什么在练习中传递了一个函数?这是故意的吗?
慕慕森
慕神8447489
随时随地看视频慕课网APP
相关分类