0

I'm trying to return a dynamic array of structs created on the fly from storage data, similar to how we return ViewModel from DB data in MVC. What is the best way of doing it in Solidity?

  • Tried creating a dynamic memory array, but couldn't use push.
  • Tried creating a dynamic storage array, but it said, Uninitialized storage pointer.
  • If I declare the output array on the contract level, it won't let me push, because it would modify the array.
0

After re-reading Solidity docs, I have realized that I still can declare a dynamic memory array in a view and initialize its dimensions to a variable (as opposed to declaring a fixed-size array which would need a compile-time constant):

Record[] memory records = findRecords();  //get records from storage
ViewModel[] memory results = new ViewModel[](records.length);  //initialize the output array
for (uint index = 0; index < records.length; index++) {
    results[index] = getResultFromRecord(records[index]);  //convert a storage record into a ViewModel
}
return results;

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.