Solidity-Learning

Solidity 学习笔记

View the Project on GitHub XdpCs/Solidity-Learning

010-映射(Mapping)

背景

通过学习Solidity,然后输出文章检验自己的学习成果Github仓库

欢迎大家关注我的X

基础知识

例子

例子

该例子是使用映射(Mapping)的例子

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


contract Mapping {
    mapping(address => uint) public map;
    mapping(ValueContract => uint) public contractMap;

    function getMap(address _addr) public view returns (uint){
        return map[_addr];
    }

    function setMap(address _addr, uint _i) public {
        map[_addr] = _i;
    }

    function removeMap(address _addr) public {
        delete map[_addr];
    }

    function getContractMap(ValueContract _addr) public view returns (uint){
        return contractMap[_addr];
    }

    function setContractMap(ValueContract _addr, uint _i) public {
        contractMap[_addr] = _i;
    }

    function removeContractMap(ValueContract _addr) public {
        delete contractMap[_addr];
    }
}

contract NestedMapping {
    mapping(address => mapping(uint => bool)) public nested;

    function get(address _addr, uint _i) public view returns (bool){
        return nested[_addr][_i];
    }

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

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

contract ValueContract {
    uint public value;

    constructor(uint _value) {
        value = _value;
    }
}

程序解析

ValueContract 合约

contract ValueContract {}

Mapping 合约

mapping(address => uint) public map;
mapping(ValueContract => uint) public contractMap;
function getMap(address _addr) public view returns (uint){
    return map[_addr];
}

function getContractMap(ValueContract _addr) public view returns (uint){
    return contractMap[_addr];
}
function setMap(address _addr, uint _i) public {
    map[_addr] = _i;
}

function getContractMap(ValueContract _addr) public view returns (uint){
    return contractMap[_addr];
}
function removeMap(address _addr) public {
    delete map[_addr];
}

function removeContractMap(ValueContract _addr) public {
    delete contractMap[_addr];
}

NestedMapping 合约

mapping(address => mapping(uint => bool)) public nested;
function get(address _addr, uint _i) public view returns (bool){
    return nested[_addr][_i];
}
 function set(address _addr, uint _i, bool _boo) public {
    nested[_addr][_i] = _boo;
}
function remove(address _addr, uint _i) public {
    delete nested[_addr][_i];
}

链接