7

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.

5

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

3

There is no built-in support for this in Solidity.

A workaround is to create a factory method where you can initialize the fields:

function createAttributeStats() public returns (AttributeStats memory attrStats) {
    attrStats = AttributeStats(now, 1, 356, 0);
}
  • You can't do AttributeStats() without parameters – folex Jan 15 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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