DEV Community

Cover image for Day 14 - Mappings
Vedant Chainani
Vedant Chainani

Posted on • Updated on

Day 14 - Mappings

GitHub logo Envoy-VC / 30-Days-of-Solidity

30 Days of Solidity step-by-step guide to learn Smart Contract Development.

This is Day 14 of 30 in Solidity Series
Today I Learned About Mappings in Solidity.

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>;
Enter fullscreen mode Exit fullscreen mode

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;
    }
}
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)