为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我的解决方案对于 go slices 练习不正确?

为什么我的解决方案对于 go slices 练习不正确?

Go
慕慕森 2022-10-10 17:54:03
我正在学习 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 mainimport "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我不确定我在这里做错了什么。另外,为什么在练习中传递了一个函数?这是故意的吗?
查看完整描述

1 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

好,我知道了。正如我在评论中所说,您应该用slice[j] = uint((i+j)/2)and替换您的附加调用ans[i] = slice

该练习使用 256x256 调用您的函数。您创建一个 256 长的切片,然后将其他切片附加 256 次,得到一个 512 长的切片ans。前 256 个条目是空的,因为 appendslice在末尾追加。因此,当 pic 库迭代您的数据时,它会尝试访问一个空切片。

更新:修复算法的另一种方法是初始化长度为 0 的切片。所以编辑

ans := make([][]uint8, 0)和 slice := make([]uint8, 0)

也应该给出正确的结果。


查看完整回答
反对 回复 2022-10-10
  • 1 回答
  • 0 关注
  • 162 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号