2020.코딩일지
[solidity] mapping/array (feat.솔리디티깨부수기) 본문
728x90
1. mapping
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
//키를알면 값을 바로 뽑아서 쓸 수 있는데, length는 구할 수 없다!
contract lec13 {
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];
}
//------------------------------------------------
mapping(string=>uint256) private priceList;
function setPriceList(string memory _itemName, uint256 _price) public {
priceList[_itemName] = _price;
}
function getPriceList(string memory _index) public view returns(uint256) { //🚧키값에 itemName을입력해야 값이나옴
return priceList[_index];
}
//------------------------------------------------
mapping(uint256=>string) private nameList;
function setNameList(uint _index, string memory _name) public {
nameList[_index] = _name;
}
function getName(uint256 _index) public view returns(string memory) {
return nameList[_index];
}
}
2. array
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract let14 {
uint256[] public ageArray;
uint256[10] public ageFixedSizeArray; //인덱스0~9까지만 입력가능
string[] public nameArray = ["Kal", "Jhon", "Kerri"]; //기본3개고정 이후 추가됨
function AgeLength() public view returns(uint256){
return ageArray.length;
}
// 0 -> 50/ 1 ->70/ length : 2
function AgePush(uint256 _age) public {
ageArray.push(_age);
}
// 1 -> 70
function AgeGet(uint256 _index) public view returns(uint256){
return ageArray[_index];
}
//0 -> 50/ length : 1
function AgePop() public {
ageArray.pop();
}
// 0 -> 0, 1 -> 70/ length : 2 .. delete는 값만 삭제한다.
function AgeDelete(uint256 _index) public {
delete ageArray[_index];
}
// 0 -> 90/ 1 -> 70/ length : 2 .. index에3을넣으면 에러뱉(없으니까)
function AgeChange(uint256 _index, uint256 _age) public {
ageArray[_index] = _age;
}
}
3. mapping과 array에 주의할점
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract lec15 {
uint256 num = 89;
mapping(uint256 => uint256) numMap;
uint256[] numArray;
function changeNum(uint256 _num) public {
num = _num;
}
function showNum() public view returns(uint256) {
return num;
}
//mapping
function numMapAdd() public {
numMap[0] = num;
}
function showNumMap() public view returns(uint256) {
return numMap[0];
}
//array
function numArrayAdd() public {
numArray.push(num);
}
function showNumArray() public view returns(uint256) {
return numArray[numArray.length-1];
}
}
'Block Chain' 카테고리의 다른 글
[solidity] if문/반복문/continue와break/equal (feat.솔리디티깨부수기) (0) | 2022.12.05 |
---|---|
[solidity] struct구조체 (feat.솔리디티깨부수기) (0) | 2022.11.30 |
[solidity] event/indexed/super (feat.솔리디티깨부수기) (0) | 2022.11.29 |
[solidity] instance(분신)-constructor/상속/overriding (feat.솔리디티깨부수기) (0) | 2022.11.28 |
[solidity] 저장영역4가지 (feat.솔리디티깨부수기) (0) | 2022.11.28 |
Comments