Solidity

如何初始化結構數組

  • March 29, 2022

我想初始化一個結構數組:

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

我得到一個編譯錯誤:

“UnimplementedFeatureError:複製類型結構

$$ … $$尚不支持記憶體到儲存。

我只想初始化一個結構數組。我寧願不要在建構子中一個一個地推送“人”的新實例。關於我應該做什麼的任何想法?

在聲明尚未實現之後立即初始化結構的儲存數組。

但是,您可以聲明它,然後在函式中為其賦值(無論是建構子還是另一個)

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

非常簡單。

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)

然後使用的陣列將是personspeople取決於您的選擇。

引用自:https://ethereum.stackexchange.com/questions/99432