Consider the following Solidity code snippet:
pragma solidity ^0.8.0;
contract Test {
mapping(address => uint) public balances;
function setBalance(address user, uint amount) public {
balances[user] = amount;
}
function getBalance(address user) public view returns (uint) {
return balances[user];
}
}If no balance has been set for address 0x1234..., what will getBalance(0x1234...) return?
pragma solidity ^0.8.0; contract Test { mapping(address => uint) public balances; function setBalance(address user, uint amount) public { balances[user] = amount; } function getBalance(address user) public view returns (uint) { return balances[user]; } }
Think about what default values Solidity returns for mappings when a key is not set.
In Solidity, mappings return the default value of the value type if the key does not exist. For uint, the default is 0.
Mappings in Solidity do not support iteration. Why is this the case?
Think about how mappings are stored in the Ethereum storage.
Mappings in Solidity are implemented as hash tables without storing keys explicitly. This means the contract cannot know which keys exist, so iteration is not possible.
Examine this Solidity code snippet:
pragma solidity ^0.8.0;
contract Example {
mapping(uint => string) public data;
function addData(uint key, string memory value) public {
data[key] = value;
}
function getData(uint key) public view returns (string memory) {
return data[key];
}
function deleteData(uint key) public {
delete data[key];
}
function test() public {
string memory val = data[1];
val = "new value";
}
}What error will occur when compiling or running this contract?
Check if the operations on mapping and string memory variables are valid.
The code compiles and runs fine. Assigning to a memory variable is allowed. Deleting a mapping element sets its value to default (empty string). Mappings can have string values.
Given this Solidity contract snippet:
pragma solidity ^0.8.0;
contract Counter {
mapping(address => uint) public counts;
function increment() public {
counts[msg.sender]++;
}
function reset(address user) public {
counts[user] = 0;
}
}If msg.sender calls increment() three times, then reset(msg.sender) once, what is the value of counts[msg.sender]?
Think about what the reset function does to the mapping value.
The increment() function increases the count by 1 each call. After three calls, the count is 3. The reset() function sets the count back to 0.
Consider these Solidity mapping declarations. Which one will cause a compilation error?
Think about what types are allowed as mapping values in Solidity.
Mappings cannot have function types as values. Options A, C, and D are valid. Option A tries to use a function type as a value, which is not allowed.