40

I have a mapping like this:

struct data {  
   string name;  
   string nickname;  
}

mapping(address => data) public user;

What is the correct way to delete one element from the variable user? Do I only have to call delete(user[address])

or

do I also have to delete user[address].name and user[address].nickname?

0

1 Answer 1

47

Yes, delete user[someAddress]; will work with structs that do not contain a mapping.

For this question, because name and nickname are not mappings, they will be deleted (set to zero) automatically: there is no need to do something like "delete user[someAddress].name".

http://solidity.readthedocs.io/en/develop/types.html#delete

if you delete a struct, it will reset all members that are not mappings and also recurse into the members unless they are mappings

Caveat:

delete has no effect on whole mappings (as the keys of mappings may be arbitrary and are generally unknown)

6
  • 1
    What will happen with the data in user[someaddres].name and user[someaddress].nickname of the example above, when I do delete user[someAddress]? Will they be deleted as well or do I have to delete them before I do delete user[someAddress]?
    – Bumblebee
    Commented Apr 18, 2017 at 11:04
  • Thanks for the comment, I added to the answer to make it clearer.
    – eth
    Commented Apr 19, 2017 at 0:09
  • Does this mean "delete" doesn't free storage space, to delete and set to zero are two different things, no?
    – Jaime
    Commented Mar 31, 2018 at 10:43
  • 2
    @Jaime "delete" in a smart contract is just setting values to zero. Recovering disk space is an implementation detail and up to the node: it might see a zero and do "pruning", but it might not.
    – eth
    Commented Apr 1, 2018 at 9:26
  • Deleting elements from an array and re-arranging it to eliminate holes does save gas in the form of gas refund (an amount is subtracted from your gas cost). Is there not something similar with mappings?
    – Qwerty
    Commented Jan 5, 2022 at 16:17

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.