76

I have a struct like so :

struct fooStruct {
  uint foo;
  uint figther;
}

I would like to initialize that struct but it won't be stored in a mapping but inside an array.

Is there a way to initialize the struct like

fooStruct myStruct = fooStruct.new(par1,2,3)

1
  • 3
    good question. Not covered well in the solidity docs. This saved me a goo dchunk of time today.
    – Paul S
    Mar 19, 2016 at 0:37

1 Answer 1

98

Yes, just use

fooStruct myStruct = fooStruct(1,2);

Or

fooStruct myStruct = fooStruct({foo:1, fighter:2});

Or

fooStruct memory myStruct; // for temporary data
myStruct.figther = 2; // will only write to memory

fooStruct storage myStruct = ...; // for persistent data, has to be initialized from a state variable. `storage` is the default and a warning will be thrown by Solidity compiler versions starting with 4.17
myStruct.fighter = 2; // will write directly to storage

See the docs for more examples

6
  • 1
    Great! can you do fooStruct myStruct = fooStruct(); myStruct.figther = 2; ?
    – jayD
    Feb 19, 2016 at 18:38
  • Added an example Feb 20, 2016 at 1:23
  • @Tjaden, What if one of the members is optional. How should defining the struct or assigning change? Eg: if I want the fighter to have a predefined value or NULL value.
    – 11t
    Mar 5, 2017 at 15:25
  • 1
    The value of each member will default to the 0 value for that type (0 for ints, false for bools, etc.). If you want to have a "default" value that is different from the "0" value, you can either have a bool that indicates a value was set to "0", as opposed to defaulting to 0. You can also use a trick where you use the most significant bit of each value as the "set" bit, then just use the rest as for the actual value. Mar 5, 2017 at 18:59
  • Does solidity array has a filter/first functions which accept a lambda predicate?
    – dc7a9163d9
    Jan 2, 2018 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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