State variables are a crucial component of Solidity smart contracts. They store persistent data on the Ethereum blockchain, making them essential for maintaining contract state across transactions.
State variables in Solidity are declared outside of functions and stored permanently in contract storage. They represent the contract's state and can be accessed by any function within the contract.
To declare a state variable, simply specify its type and name at the contract level:
contract MyContract {
uint256 public myNumber;
address public owner;
bool private isActive;
}
State variables can have different visibility levels:
You can also specify mutability:
State variables can be initialized at declaration or in the constructor:
contract MyContract {
uint256 public myNumber = 42;
address public immutable owner;
constructor() {
owner = msg.sender;
}
}
State variables consume storage space and, consequently, gas. It's important to optimize their usage:
When working with state variables, keep these tips in mind:
Here's a practical example demonstrating the use of state variables in a simple voting contract:
contract Voting {
mapping(address => bool) public hasVoted;
mapping(string => uint256) public voteCount;
uint256 public totalVotes;
function vote(string memory candidate) public {
require(!hasVoted[msg.sender], "Already voted");
hasVoted[msg.sender] = true;
voteCount[candidate]++;
totalVotes++;
}
}
In this example, we use state variables to track votes, ensuring each address can only vote once and maintaining a count for each candidate.
State variables are fundamental to Solidity smart contracts, enabling persistent data storage on the blockchain. By understanding their declaration, visibility, and best practices, you can create more efficient and secure smart contracts for your decentralized applications.
For more advanced topics, explore Solidity gas optimization and Solidity security considerations.