TransWikia.com

Delete function affects my array in my struct

Ethereum Asked on December 4, 2021

I am using the function mentioned below to delete a user (i added delete entityList[rowToDelete] to the function )My main issue is that the function deletes the user but somehow I lose the data in string items[] from other users

struct EntityStruct {

    uint entityData;
    // other stuff
    string items[];   <--------- I lose the data in here/Cannot fetch the data from the array anymore
}

mapping(address => EntityStruct) public entityStructs;
address[] public entityList;

function deleteEntity(address entityAddress) public returns(bool success) {
    if(!isEntity(entityAddress)) throw;
    uint rowToDelete = entityStructs[entityAddress].listPointer;
    address keyToMove   = entityList[entityList.length-1];
    entityList[rowToDelete] = keyToMove;
    entityStructs[keyToMove].listPointer = rowToDelete;
    entityList[rowToDelete]
    entityList.length--;
    return true;
}

Mapped Structs with Delete-enabled Index by “Rob Hitchens”

One Answer

You've got an array of strings inside the entity. This is valid but not necessarily what you want.

Each entity contains a list. When you delete an entity, you delete the list that was inside it.

If that's surprising or unintended, possibly what you really want is two entities. There may be a relationship between the entities that you want to enforce at the contract level. In that case, the general idea is to hold a list of related keys in this entity, and hold the records that are supposed to survive in a separate structure.

More on that pattern over here: https://medium.com/@robhitchens/enforcing-referential-integrity-in-ethereum-smart-contracts-a9ab1427ff42

Hope it helps.

Answered by Rob Hitchens on December 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP