25

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
33

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)

4
  • 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 0: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 1 '18 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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