Skip to content

Latest commit

 

History

History
70 lines (51 loc) · 2.02 KB

File metadata and controls

70 lines (51 loc) · 2.02 KB

30 Days Of Solidity: Mappings

Twitter Follow

Author: Vedant Chainani
June, 2022

<< Day 13 | Day 15 >>

Day 14


📔 Day 14

Mapping in Solidity acts like a hash table or dictionary in any other language. These are used to store the data in the form of key-value pairs, a key can be any of the built-in data types but reference types are not allowed while the value can be of any type. Mappings are mostly used to associate the unique Ethereum address with the associated value type.

Syntax:

mapping(key => value) <access specifier> <name>;

Example:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

contract Mappings {
    struct Student {
        string name;
        string subject;
        uint marks;
    }

    mapping(address => Student) public addressToStudent;
    Student student1;

    function addDetails() public {
        student1 = Student("Daniel","Maths",85);
        addressToStudent[0x5B38Da6a701c568545dCfcB03FcB875f56beddC4] = student1;
    }
}

Here we map a address to a Student struct.and the function addDetails adds the details of the student to struct student1 and then maps it to address 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4.

Output when we pass the above address in addressToStudent mapping:

{
	"0": "string: name Daniel",
	"1": "string: subject Maths",
	"2": "uint256: marks 85"
}

<< Day 13 | Day 15 >>