我想制作一个结构的二维数组,但是我收到一个错误

时间:2016-05-13 03:31:17

标签: go

这是我的代码:

type Square struct {
    num int //Holds the number. 0 is empty
}

func somefunc() {
    squares := [4][4]Square

但是我收到了这个错误:

type [4][4]Square is not an expression

2 个答案:

答案 0 :(得分:5)

使用squares := [4][4]Square{}完成复合文字,或使用var squares [4][4]Square声明变量。

答案 1 :(得分:0)

2d数组和初始化:

package main

import (
    "fmt"
)

type Square struct {
    num int //Holds the number. 0 is empty
}

func main() {
    squares0 := [4][4]Square{} // init to zeros
    fmt.Println(squares0)

    var squares [4][4]Square // init to zeros
    fmt.Println(squares)

    squares2 := [4][4]Square{{}, {}, {}, {}} // init to zeros
    fmt.Println(squares2)

    squares3 := [4][4]Square{
        {{1}, {2}, {3}, {4}},
        {{5}, {6}, {7}, {8}},
        {{9}, {10}, {11}, {12}},
        {{13}, {14}, {15}, {16}}}
    fmt.Println(squares3)

    for i := 0; i < 4; i++ {
        for j := 0; j < 4; j++ {
            squares[i][j].num = (i+1)*10 + j + 1
        }
    }
    fmt.Println(squares)
}

输出:

[[{0} {0} {0} {0}] [{0} {0} {0} {0}] [{0} {0} {0} {0}] [{0} {0} {0} {0}]]
[[{0} {0} {0} {0}] [{0} {0} {0} {0}] [{0} {0} {0} {0}] [{0} {0} {0} {0}]]
[[{0} {0} {0} {0}] [{0} {0} {0} {0}] [{0} {0} {0} {0}] [{0} {0} {0} {0}]]
[[{1} {2} {3} {4}] [{5} {6} {7} {8}] [{9} {10} {11} {12}] [{13} {14} {15} {16}]]
[[{11} {12} {13} {14}] [{21} {22} {23} {24}] [{31} {32} {33} {34}] [{41} {42} {43} {44}]]