Solidity0.8.0-映射

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;

//mapping
//how to declare a mapping (simple and nested)
//Set, get ,delete
//["alice", "bob", "charlie"] //做一个映射查找数组元素比遍历省gas费
//{"alice":true, "bob":true, "charlie":true}//拿bob变量名称去映射里返回他的值,如果不是true则这个bob值在数组不存在
contract Mapping {
    mapping(address => uint) public balances;//记账式类型,针对某个地址记录他的账本余额,一个地址对应一个数字就是账本映射
    mapping(address => mapping(address => bool)) public isFriend;//嵌套式映射,查询2个映射返回值是否true判断是否是friend

    function examples() external {
        balances[msg.sender] = 123;
        uint bal = balances[msg.sender];    
        uint bal2 = balances[address(1)]; //数组中不存在的值默认返回uint,uint默认值为0

        balances[msg.sender] += 456; //123+456 = 579
        delete balances[msg.sender]; //删除之后恢复到默认值,并不是真正删除,0

        isFriend[msg.sender][address(this)] = true;//嵌套式赋值
    }
}

 

posted @ 2022-07-28 23:37  ZaleSwfit  阅读(60)  评论(0编辑  收藏  举报