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