2

I have a problem that when I try to delete a struct having mapping inside from its array without leaving a gap, it always says Types in storage containing (nested) mappings cannot be assigned to.
I understand why it forbids me from doing it but I cant find a solution.

These are my structs, because I have problems with using User[] user inside Card struct, (I can't call something like cards[i].users[msg.sender]) so I used mapping inside Card struct instead:

struct User {
    uint purchaseDate;
}    
struct Card {
    string name;
    uint price;
    uint lifeSpan;
    mapping (address => User) users;
}
mapping(uint => Card) public cards;

I want to delete one element without leaving a gap like this:

function deleteCard(uint _id) public isOwner {
    require(0 < _id || _id > types, "Card does not exist");
    for (uint i = _id; i < types; i++) {
        cards[i] = cards[i+1];    // error
    }
}

So how to delete it like that? Or how to copy data from cards[i+1].users to cards[i].users? Because Solidity also does not have for loop by keys for mapping too.

Im new to Solidity, so any answer from you guys are all appreciated, thank you everyone.

1

1 Answer 1

2

that's not really the way mappings work as they're not enumerable and you can only reset the values to default as a form of "delete".

The way you're thinking of them is akin to an array, which you could enumerate.

if you stick with a mapping, you can only reset/set to zero, the mapping. if you use an array instead, you can delete items, but even that is a bit fiddly and can be gassy. It's not bad if the order of the items doesn't matter. In which case you can copy the last item of the array into the position you can to delete, and then .pop() the last item off the end of the array

1
  • As you said, then there is no way to delete without leaving a gap like that? Do you have any suggestion? Because if I dont use mapping, I will have problem with caling cards[i].users[msg.sender]. Im really stuck and looking for help, thank you very much, sir.
    – SnowyField
    Commented Aug 31, 2022 at 12:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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