In Solidity, storage
is a data location where variables can be stored permanently on the blockchain. Variables declared in storage
are state variables and retain their values between function calls and transactions.
Characteristics of Storage Variables
- Permanence: Variables in
storage
persist on the blockchain and maintain their values until explicitly changed or deleted. - Gas Costs: Writing to
storage
is more expensive in terms of gas compared tomemory
because it involves writing data to the blockchain. - Accessibility: Storage variables can be accessed by all functions within the contract and can be of various types, including arrays, structs, and mappings.
Declaring a Storage Variable
To declare a variable in storage
, simply define it at the contract level without any special keywords. Here’s an example:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract StorageExample {
// Declaring a state variable in storage
uint256 public storedData; // This is a storage variable
// Function to set the value of storedData
function setStoredData(uint256 data) public {
storedData = data; // Writing to storage
}
// Function to get the value of storedData
function getStoredData() public view returns (uint256) {
return storedData; // Reading from storage
}
}
How to Interact with Storage Variables
Once you have declared a storage variable, you can interact with it using functions. In the example above, the setStoredData
function allows you to write a value to the storedData
variable, while the getStoredData
function retrieves the current value of storedData
.
Conclusion
Declaring a variable in storage
is straightforward in Solidity. By defining state variables at the contract level, you can create persistent data that retains its value across function calls. Understanding how to use storage
effectively is essential for building robust smart contracts on the Ethereum blockchain.