In Solidity, initializing an array of structs with predefined values directly in the declaration is not straightforward due to certain limitations in how memory and storage data are handled. As of my last update, Solidity doesn't support the direct initialization of an array of structs with predefined values in the way you've shown in your example. The error you're encountering is due to this limitation.
However, you can achieve your goal by initializing the array within a constructor. While you prefer not to use the push method in a constructor, it's currently one of the viable ways to initialize an array of structs with predefined values.
Here's how you can modify your code to achieve this:
pragma solidity ^0.8.0; contract MyContract { struct Person { string firstName; string lastName; } Person[3] public family; constructor() { family[0] = Person("Will", "Smith"); family[1] = Person("Jada", "Smith"); family[2] = Person("Brad", "Pitt"); } }
In this approach:
The family array is declared without initial values. The constructor of the contract is used to initialize each element of the array. This is done by directly assigning a new Person struct to each index of the family array. This method ensures that your family array is initialized with the desired values when the contract is deployed, without needing to call push multiple times. It's a straightforward workaround for the current limitation in Solidity regarding direct array of struct initialization.