Mappings
Part of the Fundamentals section of Coddy's Solidity journey. Lesson 42 of 53.
A mapping associates keys with values in storage. Declare mapping(keyType => valueType) at contract scope and use square brackets to read or write a key. An unwritten key yields the default value of the value type, such as zero for uint256.
Declare this at contract scope:
mapping(uint256 => uint256) points;Use it inside the provided main function:
points[4] = 18;
console.log(points[4]);
console.log(points[5]);The assignment changes only key four. Key five has never been assigned and reads as zero. A mapping does not provide a length or a built-in list of its keys; track keys separately if an application needs iteration.
An unwritten mapping key reads as the default value of its value type.
Challenge
EasyDeclare a mapping from uint256 keys to uint256 values named scores. Assign points to key player, then print scores[player] and scores[player + 1].
The tests pass arguments to main in this order: uint256 player, uint256 points. Each test starts with fresh contract state.
Use console.log for the requested output. Print only the requested values, one per line, with no extra labels unless the task specifies them.
Try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
import "forge-std/console.sol";
contract Main {
function main(uint256 player, uint256 points) external {
// Write your solution here.
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
Practice on your own: Solidity playground