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?

Achala Dissanayake
  • 5,819
  • 15
  • 28
  • 38
Bumblebee
  • 1,751
  • 3
  • 14
  • 23

1 Answers1

46

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)

eth
  • 85,679
  • 53
  • 285
  • 406
  • 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 Apr 18 '17 at 11:04
  • Thanks for the comment, I added to the answer to make it clearer. – eth Apr 19 '17 at 00:09
  • Does this mean "delete" doesn't free storage space, to delete and set to zero are two different things, no? – Jaime Mar 31 '18 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 Apr 01 '18 at 09: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 Jan 05 '22 at 16:17
  • @Qwerty Refunds have been reduced in EIP-3529. – eth Jan 10 '22 at 04:51