Solidity 솔리디티 강좌 17강 : Mapping(맵핑)

flowing1ife·2023년 7월 7일
0

[ Solidity 깨부수기 ]

목록 보기
17/29
post-thumbnail

Solidity 솔리디티 강좌 17강 : Mapping(맵핑)
이번엔 solidity의 mapping에 대해 알아보도록 하자.


Mapping

📌 Solidity

mappingkeyvalue로 이루어져 있다. 또한 array와 달리 length를 구할 수 없다는 것이 특징이다.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.9.0;

contract lec17 {
   
   mapping (uint256 => uint256) private ageList;
   
   function setAgeList(uint256 _index, uint256 _age) public {
       ageList[_index] = _age;
   }

   function getAge(uint256 _index) public view returns(uint256){
       return ageList[_index];
   }
}

ageList라는 mapping을 만들고 key와 value 모두 data type을 uint256으로 지정했다. 이처럼 mapping을 선언할 때에는 mapping(key data type => value data type) mapping 명 순으로 작성한다.

setAgeList 함수는 ageList에 인자로 받아온 _index 값을 key로, _age 값을 value로 하는 mapping을 set한다.

getAge 함수는 ageList에서 인자로 받아온 _index 값을 key로 하는 value값을 return한다.

👉 결과

3 => 21로 mapping을 하고 getAge 함수에 3을 인자로 하여 호출했더니 21이 return이 되었다.

mapping을 더 다양하게 선언해보자.

// SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.7.0 < 0.9.0;

contract lec17 {
   
   mapping (uint256 => uint256) private ageList;
   mapping (string => uint256) private priceList;
   mapping (uint256 => string) private nameList;

   
   function setAgeList(uint256 _index, uint256 _age) public {
       ageList[_index] = _age;
   }

   function getAge(uint256 _index) public view returns(uint256){
       return ageList[_index];
   }

   function setNameList(uint256 _index, string memory _name) public {
       nameList[_index] = _name;
   }

   function getName(uint256 _index) public view returns(string memory){
       return nameList[_index];
   }

   function setPriceList(string memory _itemName, uint256 _price) public {
       priceList[_itemName] = _price;
   }

   function getPrice(string memory _itemName) public view returns(uint256){
       return priceList[_itemName];
   }
}

👉 결과

nameList2 => Kim 을, priceListmouse => 10000 으로 설정하고 각각을 key 값으로 불러보았더니 key에 맞는 value값이 불러졌다.


출처 및 참고 자료

profile
👩🏻‍💻 Backend Engineer, Contract Developer

0개의 댓글