Solidity Mapping – How to Delete an Element from a Mapping

contract-developmentmappingsoliditystruct

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?

Best Answer

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)

Related Topic