2

I was wondering what is the best practice for initializing a struct which is a member of an Array?

I want to fill my smart contract with some information upon initializing it. That I intend to mainly store in an array, so it is stored in a coherent way when later adding more information.

I am currently doing it in a similar matter as below. It can get a bit messy though and was looking for a better way.

contract ExampleContract {

struct ExampleStruct {
    address owner,
    string text
}

ExampleStruct[] public exampleStructs;

function ExampleContract( address myAddress, string myText ) {
    ExampleStruct memory es;

    es.owner = myAddress;
    es.text = myText;

    exampleStructs.push(es);
}

...

}

Thanks

2

If you're just going to put it in storage anyway, there's no reason to declare a memory struct. Just do:

contract ExampleContract {

struct ExampleStruct {
    address owner;
    string text;
}

ExampleStruct[] public exampleStructs;

function ExampleContract( address myAddress, string myText ) {
    exampleStructs.push(ExampleStruct(myAddress, myText));
}

...

}
  • What if ExampleStruct had a parameter uint[] x. How would I modify exampleStructs.push(ExampleStruct(myAddress, myText) to also initialize x to an empty array? – Manan Mehta Nov 15 '17 at 21:09

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.