Mapping is defined as any other variable type, which accepts a key type and a value type.
Example: In the below example, the contract mapping _example a structure is defined and mapping is created.
// Solidity program to
// demonstrate mapping
pragma solidity ^0.4.18;
contract mapping_example {
//Defining structure
struct student
{
// Declaring different
// structure elements
string name;
string subject;
uint8 marks;
}
// Creating a mapping
mapping (address => student) result;
address[] public student_result;
}
}
To add values to a mapping in Solidity, you can use the following approaches:
Direct Assignment: You can assign a value to a specific key in the mapping using the assignment operator (=). For example:
mapping(address => uint) public balances;
function addBalance(address account, uint amount) public {
balances[account] = amount;
}
Struct Initialization: If the mapping value is a struct, you can initialize the struct and assign it to a specific key in the mapping. For example:
struct Student {
string name;
uint age;
}
mapping(address => Student) public students;
function addStudent(address account, string memory name, uint age) public {
students[account] = Student(name, age);
}
Function Calls: You can define functions within your contract that add values to the mapping based on certain conditions or calculations. For example:
mapping(address => uint) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
These are some of the common ways to add values to a mapping in Solidity. The specific approach depends on your use case and requirements. Remember to consider access control, input validation, and other necessary checks when adding values to mappings to ensure the integrity of your data.
To retrieve values from a mapping in Solidity, you can simply access the mapping using the corresponding key. Here are some examples: