{"id":7520,"date":"2024-03-29T04:49:53","date_gmt":"2024-03-29T04:49:53","guid":{"rendered":"https:\/\/metaschool.so\/articles\/?p=7520"},"modified":"2024-03-29T04:49:57","modified_gmt":"2024-03-29T04:49:57","slug":"understand-mappings-in-solidity","status":"publish","type":"post","link":"https:\/\/metaschool.so\/articles\/understand-mappings-in-solidity\/","title":{"rendered":"Understand mappings in Solidity"},"content":{"rendered":"<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_56_1 ez-toc-wrap-left counter-hierarchy ez-toc-counter ez-toc-custom ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title \" >Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/metaschool.so\/articles\/understand-mappings-in-solidity\/#Think_of_a_Telephone_Directory_But_on_the_Blockchain\" title=\"Think of a Telephone Directory, But on the Blockchain\">Think of a Telephone Directory, But on the Blockchain<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/metaschool.so\/articles\/understand-mappings-in-solidity\/#Declaring_and_Initializing_Mappings\" title=\"Declaring and Initializing Mappings\">Declaring and Initializing Mappings<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/metaschool.so\/articles\/understand-mappings-in-solidity\/#Adding_and_Retrieving_Data\" title=\"Adding and Retrieving Data\">Adding and Retrieving Data<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/metaschool.so\/articles\/understand-mappings-in-solidity\/#Example_Keeping_Track_of_High_Scores_in_a_Game\" title=\"Example: Keeping Track of High Scores in a Game\">Example: Keeping Track of High Scores in a Game<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/metaschool.so\/articles\/understand-mappings-in-solidity\/#Key_Points_to_Remember_About_Mappings\" title=\"Key Points to Remember About Mappings\">Key Points to Remember About Mappings<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/metaschool.so\/articles\/understand-mappings-in-solidity\/#Further_Exploration_Advanced_Mapping_Techniques\" title=\"Further Exploration: Advanced Mapping Techniques\">Further Exploration: Advanced Mapping Techniques<\/a><\/li><\/ul><\/nav><\/div>\n\n<p>Imagine you&#8217;re building a complex smart contract, a self-executing program on the blockchain. You need a way to store and manage data efficiently. That&#8217;s where mappings come in \u2013 powerful tools in Solidity that act like digital dictionaries. They allow you to associate unique keys with corresponding values, making data retrieval and manipulation a breeze.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"think-of-a-telephone-directory-but-on-the-blockchain\"><span class=\"ez-toc-section\" id=\"Think_of_a_Telephone_Directory_But_on_the_Blockchain\"><\/span><strong>Think of a Telephone Directory, But on the Blockchain<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>In the real world, you use a phone directory to find phone numbers associated with specific names. Mappings work similarly in Solidity. Here&#8217;s the breakdown:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Keys:<\/strong>\u00a0These are unique identifiers that act like names in the phone directory. Keys can be of various data types like addresses, integers, or even strings.<\/li><li><strong>Values:<\/strong>\u00a0These are the actual pieces of information you want to store, like phone numbers in the directory analogy. Values can be any data type supported by Solidity, including numbers, strings, arrays, or even other mappings (nested mappings!).<\/li><\/ul>\n\n\n\n<p><strong>\ud83d\udd25 Check this course out:<\/strong>\u00a0<a href=\"https:\/\/metaschool.so\/courses\/build-marketplace-erc404-tokens\" target=\"_blank\" rel=\"noreferrer noopener\">Build a Semi-Fungible ERC404 Tokens\u2019 Marketplace<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"declaring-and-initializing-mappings\"><span class=\"ez-toc-section\" id=\"Declaring_and_Initializing_Mappings\"><\/span><strong>Declaring and Initializing Mappings<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Here&#8217;s how you declare and initialize a mapping in Solidity:<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:16px\"><code>mapping(KeyType =&gt; ValueType) public myMapping;\n\n\/\/ Example: Mapping addresses to their favorite numbers\nmapping(address =&gt; uint256) public favoriteNumbers;\n<\/code><\/pre>\n\n\n\n<p>In this example:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><code>mapping(address =&gt; uint256)<\/code>&nbsp;defines the mapping type. It tells the compiler that the mapping associates&nbsp;<code>address<\/code>&nbsp;keys (like Ethereum addresses) with&nbsp;<code>uint256<\/code>&nbsp;values (unsigned integers).<\/li><li><code>public myMapping<\/code>&nbsp;declares a variable named&nbsp;<code>myMapping<\/code>&nbsp;of the mapping type. Setting it to&nbsp;<code>public<\/code>&nbsp;allows anyone to read the values associated with keys in this mapping.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"adding-and-retrieving-data\"><span class=\"ez-toc-section\" id=\"Adding_and_Retrieving_Data\"><\/span><strong>Adding and Retrieving Data<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Now that you have your mapping set up, let&#8217;s see how to add and retrieve data:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Adding:<\/strong>\u00a0Use the assignment operator (<code>=<\/code>) to associate a value with a key. <\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:16px\"><code>favoriteNumbers&#91;msg.sender] = 42; \/\/ Assign the value 42 to the key msg.sender (sender's address<\/code><\/pre>\n\n\n\n<ul class=\"wp-block-list\"><li><strong style=\"background-color: var(--nv-site-bg); color: var(--nv-text-color); font-family: var(--bodyfontfamily); font-size: var(--bodyfontsize); letter-spacing: var(--bodyletterspacing); text-transform: var(--bodytexttransform);\">Retrieving:<\/strong><span style=\"background-color: var(--nv-site-bg); color: var(--nv-text-color); font-family: var(--bodyfontfamily); font-size: var(--bodyfontsize); font-weight: var(--bodyfontweight); letter-spacing: var(--bodyletterspacing); text-transform: var(--bodytexttransform);\">\u00a0Use the key within square brackets\u00a0<\/span><code style=\"color: var(--nv-text-color); font-size: var(--bodyfontsize); font-weight: var(--bodyfontweight); letter-spacing: var(--bodyletterspacing); text-transform: var(--bodytexttransform);\">[]<\/code><span style=\"background-color: var(--nv-site-bg); color: var(--nv-text-color); font-family: var(--bodyfontfamily); font-size: var(--bodyfontsize); font-weight: var(--bodyfontweight); letter-spacing: var(--bodyletterspacing); text-transform: var(--bodytexttransform);\">\u00a0to access the value associated with that key.<\/span><\/li><\/ul>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:16px\"><code>uint256 storedNumber = favoriteNumbers&#91;msg.sender]; \/\/ Get the favorite number stored at msg.sender's address<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"example-keeping-track-of-high-scores-in-a-game\"><span class=\"ez-toc-section\" id=\"Example_Keeping_Track_of_High_Scores_in_a_Game\"><\/span><strong>Example: Keeping Track of High Scores in a Game<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Let&#8217;s look at a more practical example. Imagine you&#8217;re building a game on the blockchain where players can compete for the highest score. You can use a mapping to track each player&#8217;s address as the key and their high score as the value:<\/p>\n\n\n\n<pre class=\"wp-block-code has-nv-site-bg-background-color has-background\" style=\"font-size:16px\"><code>mapping(address => uint256) public highScores;\n\nfunction updateHighScore(uint256 newScore) public {\n  if (newScore > highScores&#91;msg.sender]) {\n    highScores&#91;msg.sender] = newScore;\n  }\n}<\/code><\/pre>\n\n\n\n<p>In this example:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The\u00a0<code>highScores<\/code>\u00a0mapping stores player addresses as keys and their high scores as values.<\/li><li>The\u00a0<code>updateHighScore<\/code>\u00a0function checks if the new score is higher than the player&#8217;s existing score stored in the mapping.<\/li><li>If the new score is higher, the mapping is updated with the new score for that player&#8217;s address.<\/li><\/ul>\n\n\n\n<p><strong>\ud83d\udd25 Check this course out:<\/strong>\u00a0<a href=\"https:\/\/metaschool.so\/courses\/one-piece-personality-dapp-solidity\" target=\"_blank\" rel=\"noreferrer noopener\">Build a One Piece Personality dApp With Solidity<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"key-points-to-remember-about-mappings\"><span class=\"ez-toc-section\" id=\"Key_Points_to_Remember_About_Mappings\"><\/span><strong>Key Points to Remember About Mappings<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Here are some crucial aspects to remember when using mappings:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Uniqueness of Keys:<\/strong>&nbsp;Keys within a mapping must be unique. You can&#8217;t have two entries with the same key.<\/li><li><strong>Default Values:<\/strong>&nbsp;Mappings don&#8217;t have a default value. Attempting to access a non-existent key will result in an error.<\/li><li><strong>Storage vs. Memory:<\/strong>&nbsp;Mappings are stored on the blockchain, making them more expensive to access compared to memory variables. Optimize your code to minimize unnecessary mapping reads and writes.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"further-exploration-advanced-mapping-techniques\"><span class=\"ez-toc-section\" id=\"Further_Exploration_Advanced_Mapping_Techniques\"><\/span><strong>Further Exploration: Advanced Mapping Techniques<\/strong><span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>While these basics equip you with the power of mappings, Solidity offers more advanced features:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li><strong>Nested Mappings:<\/strong>&nbsp;You can create mappings within mappings for more complex data structures.<\/li><li><strong>Mapping Deletion:<\/strong>&nbsp;While there&#8217;s no direct deletion function, you can overwrite a value with a zero-value of its type to effectively remove it.<\/li><\/ul>\n\n\n\n<p>By understanding these concepts, you can leverage mappings effectively in your Solidity smart contracts for various use cases, from storing user preferences to managing complex game mechanics. Happy coding!<\/p>\n\n\n\n<p><strong>Try it out, ask us questions, and tell us how it went by tagging Metaschool on Social Media.<\/strong><\/p>\n\n\n\n<p><strong>Follow us on<\/strong>&nbsp;\u2013<\/p>\n\n\n\n<p>\ud83d\udd2eTwitter \u2013&nbsp;<a href=\"https:\/\/twitter.com\/0xmetaschool\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/twitter.com\/0xmetaschool<\/a><\/p>\n\n\n\n<p>\ud83d\udd17LinkedIn \u2013&nbsp;<a href=\"https:\/\/www.linkedin.com\/company\/0xmetaschool\/\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.linkedin.com\/company\/0xmetaschool\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"","protected":false},"author":16,"featured_media":7521,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"neve_meta_sidebar":"","neve_meta_container":"","neve_meta_enable_content_width":"","neve_meta_content_width":0,"neve_meta_title_alignment":"","neve_meta_author_avatar":"","neve_post_elements_order":"","neve_meta_disable_header":"","neve_meta_disable_footer":"","neve_meta_disable_title":"","footnotes":""},"categories":[292],"tags":[51,46,29],"class_list":["post-7520","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-answers","tag-blockchain","tag-solidity","tag-web3"],"_links":{"self":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7520","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/users\/16"}],"replies":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/comments?post=7520"}],"version-history":[{"count":1,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7520\/revisions"}],"predecessor-version":[{"id":7522,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/posts\/7520\/revisions\/7522"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media\/7521"}],"wp:attachment":[{"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/media?parent=7520"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/categories?post=7520"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/metaschool.so\/articles\/wp-json\/wp\/v2\/tags?post=7520"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}