Hey there, Are you learning solidity and want to know about mapping? Here is an article for you!
Mapping refers to a hash table consisting of key and value type pairs. This can only have a type of storage and is generally used for state variables. It can be marked public. Solidity automatically creates a getter for it.
Below is the syntax:
mapping(_KeyType => _ValueType)
Where:
**_KeyType **: can be any built-in type plus bytes and string. No reference type or complex objects are allowed.
** _ValueType**: can be any type.
Example
pragma solidity ^0.4.18;
contract mappingExample {
struct student {
string name;
string subject;
uint8 marks;
}
// Creating mapping
mapping (address => student) result;
address[] student_result;
// Function adding values to the mapping
function adding_values() public {
var student
= result[0xDEE7796E89C82C36BAdd1375076f39D69FafE252];
student.name = "John";
student.subject = "Chemistry";
student.marks = 88;
student_result.push(
0xDEE7796E89C82C36BAdd1375076f39D69FafE252) -1;
}
// Function to retrieve
// values from a mapping
function get_student_result(
) view public returns (address[]) {
return student_result;
}
}