How to Initialize a Struct?

  • 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)

    good question. Not covered well in the solidity docs. This saved me a goo dchunk of time today.

  • Tjaden Hess

    Tjaden Hess Correct answer

    5 years ago

    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

    Great! can you do `fooStruct myStruct = fooStruct();` `myStruct.figther = 2;` ?

    Added an example

    `@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.

    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.

    Does solidity array has a `filter`/`first` functions which accept a lambda predicate?

    How to initialize it from outside of the contract scope? E.g. from a test file?

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM