Solidity Struct Initialization – How to Initialize a Struct

contract-developmentsoliditystruct

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)

Best Answer

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

Related Topic