[Ethereum] How to give struct members default values

contract-deploymentcontract-developmentsolidity

I am working on some complex Relational databases like structure in solidity and need to have some values initialized to a custom value not the usual 0.

I want to do something like this :
(Status is an enum)

  struct AttributeStats {
    bytes32 ValidationDate = now;
    Status status = 1;
    bytes32 ValidationDuration = 356;
    bytes32 Value;
  }

I don't think this is supported by solidity, but i need it to happen.

Best Answer

No, this can't be done in Solidity. The reason is that there's no explicit allocation, and all slots in storage are implicitly zero until set to something else.

A pattern to use here would be to use a boolean value indicating whether a struct had been initialized (false by default because that's the zero value of a boolean), and everywhere you read a struct, check that flag and initialize if needed first. Something like this:

struct AttributeStats {
    bool initialized;
    Status status;
    bytes32 validationDuration;
    bytes32 value;
}
mapping (uint256 => AttributeStats) attributeStats;

function initializeIfNeeded(uint256 id) internal {
    AttributeStats stats = attributeStats[id];

    if (!stats.initialized) {
        stats.initialized = true;
        stats.validationDate = now;
        stats.status = 1;
        stats.validationDuration = 356;
    }        
}

function doSomething(uint256 id) public {
    initializeIfNeeded(id);

    AttributeStats storage stats = attributeStats[id];

    // ...
}

(It's unclear what now you meant to use in your pseudocode. I assumed you want to use the time when you initialize the struct, but if you wanted to use something like the time of contract creation, just store that in a variable in the constructor and use that instead.)

Related Topic