Hey Kodi,
Your logic wasn’t wrong, it’s just that the Solidity language as it currently is doesn’t (yet) support initialising a storage array of struct instances at declaration (which is what you were trying to do). We can only initialise such an array from within a function or a constructor. Because you want to deploy your contract with a pre-populated array, you need to use a constructor.
Your logical thinking itself isn’t wrong, because we can use your same logic to successfully initialise storage arrays of strings and unsigned integers, for example …
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.7.5;
contract SimpsonsStruct{
struct Simpsons{
string name;
uint price;
}
Simpsons public Homer = Simpsons("Homer", 10);
Simpsons public Marge = Simpsons("Marge", 20);
Simpsons public Bart = Simpsons("Bart", 30);
string[] simpsonsName = [Homer.name, Marge.name, Bart.name];
uint[] simpsonsPrice = [Homer.price, Marge.price, Bart.price];
function selectYourSimpson(uint _pickASimpson) view public returns(string memory, uint) {
return (simpsonsName[_pickASimpson], simpsonsPrice[_pickASimpson]);
}
}
And we can also use your same logic to successfully initialise a storage array of arrays, for example …
// SPDX-License-Identifier: UNLICENSED
pragma abicoder v2;
pragma solidity 0.7.5;
contract SimpsonsStruct{
string[2] public Homer = ["Homer", "Donuts"];
string[2] public Marge = ["Marge", "Cocktails"];
string[2] public Bart = ["Bart", "Ice Cream"];
string[2][] simpsonsIndex = [Homer, Marge, Bart];
function selectYourSimpson(uint _pickASimpson) view public returns(string memory, string memory) {
return (simpsonsIndex[_pickASimpson][0], simpsonsIndex[_pickASimpson][1]);
}
}
Both of these alternatives work perfectly well, and the only difference is that the storage arrays we are initialising at declaration contain values other than struct instances.
Both of these alternatives are almost certainly not as suitable for what you want to achieve with your contract as arrays of struct instances, but they do demonstrate quite nicely what Solidity does support in terms of initialising storage arrays, and that the logic you applied does work when Solidity supports it.
As for why Solidity doesn’t support initialising storage arrays of struct instances at declaration, but does for storage arrays of other data types, I really couldn’t tell you. There have been certain other operations involving data structures that earlier versions of Solidity haven’t supported, but which it now does support. There are also other examples that you will come across which still aren’t supported. Maybe some future version of Solidity will eventually support initialising storage arrays of struct instances in the way you tried to do it… or maybe not … I really couldn’t say.
Anyway, I hope that’s helpful as well, and restores your confidence in your own logical approach to these sorts of tasks