The delete operator can be applied to any variable to reset it to its default value. The default value is all bits assigned to 0.
If we apply delete to a dynamic array, then it deletes all of its elements and the length becomes 0. And if we apply it to a static array, then all of its indices are reset. You can also apply delete to specific indices, in which case the indices are reset.
Nothing happens if you apply delete to a map type. But if you apply delete to a key of a map, then the value associated with the key is deleted.
Here is an example to demonstrate the delete operator:
contract sample {
struct Struct {
mapping (int => int) myMap;
int myNumber;
}
int[] myArray;
Struct myStruct;
function sample(int key, int value, int number, int[] array) {
//maps cannot be assigned so while constructing struct we ignore the maps
myStruct = Struct(number);
//here set the map key/value
myStruct.myMap[key] = value;
myArray = array;
}
function reset(){
//myArray length is now 0
delete myArray;
//myNumber is now 0 and myMap remains as it is
delete myStruct;
}
function deleteKey(int key){
//here we are deleting the key
delete myStruct.myMap[key];
}
}