English 中文(简体)
类型
原标题:Slice of slices types

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
}

我不理解为什么我不得不使用<代码>make的声明>和uint8。 两种类型(见刀切的评论)。 这似乎多余,但我无法说明如何以其他方式做到这一点。

最佳回答

在戈马没有其他办法这样做。

是的,我同意,这是好事,但是必要的。 第二项声明完全独立于第一项声明。 可以认为,汇编者应当能够从<代码>[i]中推断出该类型,但此时此刻该类型并不。

另一点:如果你遗漏了第二起案件中的那类内容,那么(a)项陈述如何看待? 仍然需要做实际分配,并能够具体说明必要的透镜/能力。

顺便提一下,你将间隔时间混在一起。 演习指出,顶级证书的长度应为<代码>dy,而不是<代码>dx,如您在代码中所示。

问题回答

To be explicit, we can use parentheses to rewrite [][]uint8 as []([]uint8): a slice of (slices of type uint8).

利用make Building-in function, for a slice of category T,make(T, n)tur a slice of category /code> with longcode>n and capacity n

因此,make([][]uint8, 2)相当于make([]([]uint8, 2),其长度和容量为2的斜体,其类型为uint8,其中每一类编号为,其初始价值为零(/code>参照,长度和容量为零)。

多功能赛标有色,类似于多维带

例如,

package main

import "fmt"

func main() {
    ss := make([][]uint8, 2) // ss is []([]uint8)
    fmt.Printf("ss:    %T %v %d
", ss, ss, len(ss))
    for i, s := range ss { // s is []uint8
        fmt.Printf("ss[%d]: %T %v %d
", i, s, s, len(s))
    }
}

产出:

ss:    [][]uint8 [[] []] 2
ss[0]: []uint8 [] 0
ss[1]: []uint8 [] 0

你们可以先发照,如:

matrix2D := [][]int8{
    {1, 2, 3},
    {4, 5, 6},
}
fmt.Println(matrix2D) // [[1 2 3] [4 5 6]]




相关问题
Having many stacks with different types

I m making a C program that needs to use two stacks. One needs to hold chars, the other needs to hold doubles. I have two structs, node and stack: struct node { double value; struct node *...

Creating (boxed) primitive instance when the class is known

I need a method that returns an instance of the supplied class type. Let s assume that the supplied types are limited to such that an "empty" instance of them can be created. For instance, supplying ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

How to generate an instance of an unknown type at runtime?

i ve got the following in C#: string typename = "System.Int32"; string value = "4"; theses two strings should be taken to generate an object of the specified type with the specified value... result ...

Type reference scope

I m studying databases and am currently working on a object-relational DB project and I ve encountered a small problem with the number of possible constraints in an object table. I m using "Database ...

热门标签