Smart Contract
We have to start with something, so weāre going to start with the simplest of all examples possible. A simple mapping.
Create a new file in Remix and put in the following content:
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
contract SimpleMappingExample {
mapping(uint => bool) public myMapping;
mapping(address => bool) public myAddressMapping;
function setValue(uint _index) public {
myMapping[_index] = true;
}
function setMyAddressToTrue() public {
myAddressMapping[msg.sender] = true;
}
}
Run the Smart Contract
Mapping are an interesting datatype in Solidity. They are accessed like arrays, but they have one major advantage: All key/value pairs are initialized with their default value.
If you have a look at the example Smart Contract, youāll see that we have two mappings.
One, that maps uint256 to booleans, thatās called myMapping
.
Another one that maps addresses to booleans, that we called myAddressMapping
.
We can access a mapping with the brackets []. If we want to access the key ā123ā in our myMapping
, then weād simply write myMapping[123]
.
Our mappings here are public, so Solidity will automatically generate a getter-function for us. That means, if we deploy the Smart Contract, we will automatically have a function that looks technically like this:
function myMapping(uint index) returns (bool) {
return myMapping[index];
}
We donāt need to explicitly write the function. Also not for myAddressMapping
. Since both are public variables, Solditiy will add these auto_magic_ally.
Letās run the Smart Contract and see what happens!
Head over to the āDeploy and Run Transactionsā Plugin and run the Smart Contract:
Perfect, letās read and write to the uint => bool mapping myMapping
first.