Solidity Mappings

What is Solidity Mappings

Solidity Mappings is a container of key value pair(s), just like we have hashmap in java.

Solidity Mappings Characteristics

Sample Code1 (Without public keyword)

pragma solidity ^0.4.0;

contract GameOfLife {
    
    mapping(address => bool) playerState;

    function updateStateOfPlayer(address playerAdd, bool state) public {
        playerState[playerAdd] = state;
    }

    // We need to explicitly provide a function to fetch the values from map
    function getPlayerState(address add) public returns (bool) {
        return playerState[add];
    }
}

Sample Code2 (With public keyword)

pragma solidity ^0.4.0;

contract GameOfLife {
    
    mapping(address => bool) public playerState;
    // Looking at public keyword compiler will generate a method by the name playerState 
    // automatically which will take address as input and will return the state from mapping
    // corresponding to that address.

    function updateStateOfPlayer(address playerAdd, bool state) public {
        playerState[playerAdd] = state;
    }
}

References

SUBSCRIBE TO NEW CONTENT

Tutorials on System Design, BlockChain, Design Patterns and more sent out once a week.

Loading comments...