go - Go 练习之旅 #18 : Slices

标签 go slice

我正在尝试完成 Exercise: Slices from the Go Tour .
但是我真的不明白我被要求做什么。

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.

我有以下代码

package main

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

func Pic(dx, dy int) [][]uint8 {
    a := make([][]uint8, dy)
    return a
}

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

到目前为止,我已经创建了长度为 dy 的 slice 。但是我不明白下一步。我是否需要创建一个 for 循环,在其中我将 slice 的每个元素分配给 dx 范围内的值?我不要求代码,而是要求解释/澄清

最佳答案

Do I need to create a for loop in which I assign every element of my slice to a value in the range of dx?

是的:

  • 一个外部循环,用于为 [x] 分配一个 []uint8 大小的 dx slice ,
  • 为每个元素 a[x](它是一个 []uint8)使用内部循环 'y' 以便分配a[x][y] 与请求值(即“有趣的函数”之一,如 x^y(x+y)/2 x*y)。
    xy 是 slice 范围内的索引(a,然后是 a[x]):参见"For statements "。

我喜欢 (x ^ y) * (x ^ y):

res

作为rwilson04评论 below :

x*x + y*y is another good one

x square plus y square

Waqas Ilyas建议 the comments : y * 10000/(x + 1)

y * 10000 / (x + 1)

关于go - Go 练习之旅 #18 : Slices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25459474/

相关文章:

go - 有没有办法在 Go 中使用动态类型 slice ?

arrays - Golang中如何返回未知类型的数组?

go - 在 Go 中命名以小写字母开头的专有名词

go - 我应该使用 panic 还是返回错误?

UDP 服务器的 Go 网络最佳实践

go - golang 中无需替换的示例

go - 插入自定义时间,实现了 Scanner 和 Valuer——但仍然出错

arrays - Go 中这两种 "slice copy"方法有什么区别

javascript - 如果在字符串方法中参数为负数,我们是否仍然从零开始计数?

javascript - 如何使用 jquery 将 xxxx 表行拆分为 100 个数组并考虑舍入?