상세 컨텐츠

본문 제목

Solidity - Mapping

Programming Language/Solidity

by Yongari 2022. 12. 23. 19:20

본문

Maps are created with the syntax mapping(keyType => valueType).

맵은 구문 매핑(keyType = > valueType)을 사용하여 생성됩니다. 

 

The keyType can be any built-in value type, bytes, string, or any contract.

keyType은 기본 제공 값 유형, 바이트, 문자열 또는 계약일 수 있습니다.

valueType can be any type including another mapping or an array.

valueType은 다른 매핑 또는 배열을 포함한 모든 유형일 수 있습니다.

Mappings are not iterable.
매핑은 iterable(반복)할 수 없다.

 

코드 

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

contract Mapping {
    // Mapping from address to uint
    // 매핑 address를 키로, int를 밸류로 설정
    mapping(address => uint) public myMap;

    function get(address _addr) public view returns (uint) {
        // Mapping always returns a value.
        // 매핑은 항상 값을 반환합니다.
        // If the value was never set, it will return the default value.
		// 값이 설정되지 않은 경우 기본값이 반환됩니다.
        return myMap[_addr];
    }

    function set(address _addr, uint _i) public {
        // Update the value at this address
        
        myMap[_addr] = _i;
    }

    function remove(address _addr) public {
        // Reset the value to the default value.
        delete myMap[_addr];
    }
}

contract NestedMapping {
    // Nested mapping (mapping from address to another mapping)
    // 중첩 매핑(주소에서 다른 매핑으로 매핑)
    mapping(address => mapping(uint => bool)) public nested;

    function get(address _addr1, uint _i) public view returns (bool) {
        // You can get values from a nested mapping
        // even when it is not initialized
        return nested[_addr1][_i];
    }

    function set(
        address _addr1,
        uint _i,
        bool _boo
    ) public {
        nested[_addr1][_i] = _boo;
    }

    function remove(address _addr1, uint _i) public {
        delete nested[_addr1][_i];
    }
}

 

 

Remix 링크

 

Remix - Ethereum IDE

 

remix.ethereum.org

 

출처 : https://solidity-by-example.org/mapping/

'Programming Language > Solidity' 카테고리의 다른 글

Solidity - Enum  (0) 2022.12.25
Solidity - Array  (0) 2022.12.25
Solidity - For and While Loop  (0) 2022.12.23
Solidity - If / Else  (0) 2022.12.23
Solidity - Gas  (0) 2022.12.22

관련글 더보기