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


潇潇雨雨
浏览 113回答 2
2回答

aluckdog

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

梦里花落0921

二维数组和初始化:package mainimport (&nbsp; &nbsp; "fmt")type Square struct {&nbsp; &nbsp; num int //Holds the number. 0 is empty}func main() {&nbsp; &nbsp; squares0 := [4][4]Square{} // init to zeros&nbsp; &nbsp; fmt.Println(squares0)&nbsp; &nbsp; var squares [4][4]Square // init to zeros&nbsp; &nbsp; fmt.Println(squares)&nbsp; &nbsp; squares2 := [4][4]Square{{}, {}, {}, {}} // init to zeros&nbsp; &nbsp; fmt.Println(squares2)&nbsp; &nbsp; squares3 := [4][4]Square{&nbsp; &nbsp; &nbsp; &nbsp; {{1}, {2}, {3}, {4}},&nbsp; &nbsp; &nbsp; &nbsp; {{5}, {6}, {7}, {8}},&nbsp; &nbsp; &nbsp; &nbsp; {{9}, {10}, {11}, {12}},&nbsp; &nbsp; &nbsp; &nbsp; {{13}, {14}, {15}, {16}}}&nbsp; &nbsp; fmt.Println(squares3)&nbsp; &nbsp; for i := 0; i < 4; i++ {&nbsp; &nbsp; &nbsp; &nbsp; for j := 0; j < 4; j++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; squares[i][j].num = (i+1)*10 + j + 1&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; 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}]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go