I want to delete a struct from an array. The order doesn't matter to me so I want to do something like following where you take the last element in the array to replace the element I want to delete so that there are no gaps in the array.
mapping (address => File[]) myFiles;
function deleteFile(uint _index) public {
require(_index >= 0, "The index cannot be a negative number");
File[] memory files = myFiles[msg.sender];
require(_index < files.length, "The index is out of bound");
if (files.length == 1) {
files.pop();
} else {
File memory file = files[files.length - 1];
files[_index] = files;
files.pop();
}
}
However, pop
is not available for struct arrays. I also cannot use files.length --
since length
is read-only. How do I achieve this?
File[] storage files = myFiles[msg.sender]
. Another problem you will have with memory arrays is that changes are on memory and will be discarded if they are not explicitly saved to storage.array.length --
which doesn't seem to work anymore. Is there no way to delete an element from an array without iterating through the entire array if I wanted to leave no gap?array.pop()
, it works for array in storage.