【Solidity】Mapping的使用

Mapping就类似于Array,只是在key中放入自定义的名

以下是简单单层的mapping

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

error Unauthorized(string errorMsg,address _address);
contract test {
    mapping(address=>uint) account;

    function get(address _address)public view returns(uint){
        return account[_address];
    }
    
    function set(address _address, uint amount)public{
        account[_address] = amount;
    }

    function remove(address _address)public{
        delete account[_address];
    }
}

以下是多层的mapping, 根据班级和学生名称获取分数

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

error Unauthorized(string errorMsg,address _address);
contract test {
    //根据班级和学生名称获取分数
    mapping( uint=> mapping(string=>uint) ) score;

    function getScore(uint _class,string memory _name)public view returns(uint){
        return score[_class][_name];
    }
    
    function setScore(uint _class,string memory _name, uint _score)public{
        score[_class][_name] = _score;
    }

    function removeScore(uint _class,string memory _name)public{
        delete score[_class][_name];
    }
}

Loading

Facebook评论