Solidity Data Location and Usage
Memory
Example
function memoryVariable(string memory _exampleString) public returns (string memory) {
_exampleString = "example"; // You can modify memory
string memory newString = _exampleString; // You can use memory within a function's logic
return newString; // You can return memory
}
Call Data
Recommended by LinkedIn
Example
function calldataVariable(string calldata _exampleString) external returns (string memory) {
// cannot modify _exampleString
// but can return it
return _exampleString;
}
Storage
Example
contract VotingSystem {
// Storage variables to store the total number of votes for each candidate
mapping(string => uint256) private votesReceived;
// Function to cast a vote for a candidate
function voteForCandidate(string memory candidate) public {
// Increment the total number of votes for the candidate
votesReceived[candidate]++;
}
// Function to get the total number of votes for a candidate
function getTotalVotesForCandidate(string memory candidate) public view returns (uint256) {
return votesReceived[candidate];
}
}
Software Engineer | Full Stack Web Developer | MERN Stack
8moVery helpful!
Founder @Oklever | Blockchain Consulting & Advisory | Web 3.0 Development | Tokenization | NFT | DeFi | Decentralized applications | Digital Marketing
8mowell explained Mohammad Rizwan 🇵🇸