The delete
keyword in Solidity is used to remove a variable or reset its value to its default state. It can be applied to state variables, local variables, and elements of arrays or mappings. Using delete
is essential for managing storage efficiently and ensuring that unwanted data does not persist in your smart contract.
Usage of the Delete Keyword
- Resetting State Variables: When
delete
is applied to a state variable, it resets the variable to its default value (e.g.,0
for integers,false
for booleans, and an empty string for strings). - Removing Array Elements: For arrays,
delete
can be used to remove an element, but it does not change the array length. Instead, it resets the specified index to its default value. - Clearing Mappings: When applied to mappings,
delete
removes the key-value pair, effectively resetting the value associated with that key to its default.
Sample Code Demonstrating the Delete Keyword
Below is an example that illustrates the usage of the delete
keyword in Solidity:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract DeleteExample {
// State variable
uint256 public number;
// Array of integers
uint256[] public numbersArray;
// Mapping from address to uint256
mapping(address => uint256) public balances;
// Function to set a number
function setNumber(uint256 _number) public {
number = _number; // Set the state variable
}
// Function to delete the state variable
function deleteNumber() public {
delete number; // Reset the state variable to its default value (0)
}
// Function to add a number to the array
function addNumber(uint256 _number) public {
numbersArray.push(_number); // Add a number to the array
}
// Function to delete an element from the array
function deleteNumberFromArray(uint256 index) public {
delete numbersArray[index]; // Reset the specified index to its default value (0)
}
// Function to set a balance for an address
function setBalance(address _address, uint256 _balance) public {
balances[_address] = _balance; // Set the balance for the address
}
// Function to delete a balance for an address
function deleteBalance(address _address) public {
delete balances[_address]; // Remove the balance for the specified address
}
}
What Happens When You Use Delete?
In the example above:
- The
deleteNumber
function resets thedelete
0 state variable to0
. - The
delete
2 function resets the specified index of thedelete
3 to0
, but the length of the array remains unchanged. - The
delete
5 function removes the balance for a specific address from thedelete
6 mapping, effectively resetting it to0
.
Conclusion
The delete
8 keyword in Solidity is a powerful tool for managing data within smart contracts. It allows developers to reset variables to their default values, remove elements from arrays, and clear mappings efficiently. Understanding how to use delete
effectively can help optimize storage usage and maintain the integrity of contract data.