Regarding your other concern, that it did not work with an array of struct, here is the way to do it (read the comments):
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.16;
contract Contract {
struct User {
uint256 id;
string name;
}
User[5] users;
uint256 public userCount;
function addUser(uint256 id, string calldata name) public {
// Will revert if the userCount is greater than 5 since we declared the `users` array to be of size 5
// The .push method does not work on this array either, since we declared it with a size of 5
users[userCount++] = User(id, name);
}
}
No need to manually assign an array of struct in the constructor. As long as you declare it in the storage like User[5] users;
is enough.
For your grid example, it would look like this:
contract Test {
//uint[] public grid;
uint public constant width = 2;
uint public constant height = 3;
uint public constant MAX_ELEMENTS = width * height;
uint public currentIndex;
Grid[MAX_ELEMENTS] public grids;
struct Grid {
uint256 index;
}
function addElement(uint element) public {
// This will fail if someone tries to add more than MAX_ELEMENTS elements. Using `.push` would not fail, but would add more elements than MAX_ELEMENTS.
grids[currentIndex] = Grid(element);
++currentIndex;
}
function getGrid() public view returns(Grid[MAX_ELEMENTS] memory) {
return grids;
}
}