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)

eth
  • 85,679
  • 53
  • 285
  • 406
jayD
  • 2,462
  • 2
  • 14
  • 25
  • 3
    good question. Not covered well in the solidity docs. This saved me a goo dchunk of time today. – Paul S Mar 19 '16 at 00:37

1 Answers1

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

JohnAllen
  • 1,318
  • 1
  • 13
  • 29
Tjaden Hess
  • 37,046
  • 10
  • 91
  • 118
  • 1
    Great! can you do fooStruct myStruct = fooStruct(); myStruct.figther = 2; ? – jayD Feb 19 '16 at 18:38
  • Added an example – Tjaden Hess Feb 20 '16 at 01: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 05 '17 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. – Tjaden Hess Mar 05 '17 at 18:59
  • Does solidity array has a filter/first functions which accept a lambda predicate? – dc7a9163d9 Jan 02 '18 at 07:18
  • How to initialize it from outside of the contract scope? E.g. from a test file? – ferit Jun 07 '18 at 17:08