Reputation: 3648
Here is my code:
type Square struct {
num int //Holds the number. 0 is empty
}
func somefunc() {
squares := [4][4]Square
But I get this error:
type [4][4]Square is not an expression
Upvotes: 2
Views: 2425
Reputation:
2d array and initialization:
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)
}
output:
[[{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}]]
Upvotes: 0
Reputation: 33936
Use squares := [4][4]Square{}
to complete the composite literal, or use var squares [4][4]Square
to declare the variable.
Upvotes: 6