go - 为什么我的解决方案不适合 tour of go slices 练习?

标签 go

我正在学习 golang 并试图完成 go 之旅。我被困在 slice 练习上。在此处复制粘贴问题和我的解决方案。有人可以批评它并告诉我我在这里做错了什么吗?

问题:

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

运行时出现错误:

panic: runtime error: index out of range [0] with length 0

我不确定我在这里做错了什么。另外,为什么在练习中传递了一个函数?这是故意的吗?

最佳答案

好的,我明白了。正如我在评论中所说,您应该将追加调用替换为 slice[j] = uint((i+j)/2)ans[i] = slice .

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

更新: 修复算法的另一种方法是初始化长度为 0 的 slice 。因此编辑

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

也应该给出正确的结果。

关于go - 为什么我的解决方案不适合 tour of go slices 练习?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69782655/

相关文章:

windows - 获取固定驱动器列表

go - 避免在数据库中保存空白结构对象

character-encoding - 在 Go 中读取非 UTF-8 文本文件

sockets - 在封闭的net.Conn上写入,但返回nil错误

api View 中的 golang 后台工作进程

戈尔姆 : How to use slice as query destination

go - 处理来自 RabbitMQ 的消息时限制并发

docker 无法运行已经存在的 go 输出文件

go - 在 go 中生成一个随机 boolean 值

go - 如何从过去的某个时间开始定期启动cron作业