4

I would like to initialize an array of structs:

struct person {
  string firstName;
  string lastName;
}
person[3] family = [
  person("Will", "Smith"),
  person("Jada", "Smith"),
  person("Brad", "Pitt")
]

I get a compile error:

"UnimplementedFeatureError: Copying of type struct [...] memory to storage not yet supported.

I just want to initialize an array of Structs. I'd rather not push new instances of "person" one by one in a constructor. Any ideas on what I should do?

2 Answers 2

0

Initialising a storage array of structs right after declaring it is not implemented yet.

You can, however, declare it and then assign values to it in a function (be it the constuctor or another one)

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");
}
0

Quite Simple.

struct Person
{
    string firstName;
    string lastName;
}

Person[] public persons;
Person[4] public people;
// `people` array will be an array of the Person struct that contains only 4 elements of type `Person` struct.


persons.push(Person(firstName value, lastName value));

// To push to the people array 👇🏾
people[index] = Person(firstName value, lastName value);
// Where index can be within 0 and (4 - 1)

The array to work with will then be persons or the people depending on your choice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.