切片类型 [英] Slice of slices types

查看:44
本文介绍了切片类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在通过出色的 Tour of Go 工作.我使用以下解决方案完成了其中一项练习(#45):

I'm currently working my way through the excellent Tour of Go. I finished one of the exercises (#45) with the following solution:

func Pic(dx, dy int) [][]uint8 {
    pic := make([][]uint8, dy) /* type declaration */
    for i := range pic {
        pic[i] = make([]uint8, dx) /* again the type? */
        for j := range pic[i] {
            pic[i][j] = uint8((i+j)/2)
        }
    }
    return pic
}

我不明白为什么我必须对 uint8 类型使用一次 make 语句两次(请参见摘要中的注释).这似乎是多余的,但我不知道该怎么做.

I don't understand why I have to use a make statement with the uint8 type twice (see comments in snippet). That seems redundant but I can't figure out how to do it in an other way.

推荐答案

Go中没有其他方法可以做到这一点.

There is no other way to do this in Go.

是的,我同意这是冗长的,但有必要.第二个make()语句完全独立于第一个.可能会争辩说,编译器应该能够从 pic [i] 推断类型,但是目前还不能.

Yes, I agree it is verbose, but necessary. The second make() statement is entirely independent of the first one. It could be argued that the compiler should be able to infer the type from pic[i], but it doesn't at this point.

另一点:如果在第二种情况下省略了类型,make()语句将如何显示?仍然需要make()进行实际分配,并能够指定所需的len/capacity.

Another point: how would the make() statement look if you omitted the type in the second case? The make() is still required to do the actual allocation and to be able to specify the required len/capacity.

作为旁注,您混合了切片长度.练习指出,顶层切片的长度应为 dy ,而不是您输入代码时的 dx .

As a side note, you mixed up the slice lengths. The exercise states the top level slice should have length dy, not dx as you put in your code.

这篇关于切片类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆