为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
潇潇雨雨 2022-01-10 15:17:12
这是我的代码: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 回答

?
aluckdog

TA贡献1847条经验 获得超7个赞

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


查看完整回答
反对 回复 2022-01-10
?
梦里花落0921

TA贡献1772条经验 获得超6个赞

二维数组和初始化:


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}]]


查看完整回答
反对 回复 2022-01-10
  • 2 回答
  • 0 关注
  • 112 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信