Solidity 练习:映射

2022-12-29 Web3 Solidity

# 一、题目说明

映射就像 Python 中的哈希表或字典,它们对于快速有效的查找很有用。

# 二、任务列表

  1. 编写一个 external 函数 get(address _addr),返回 _addr 存储在 balances 中的余额。
  2. 完成函数 set(address _addr, uint _val),将 _addr 的余额设置为 _val,该函数必须是 external 的。
  3. 完成函数 remove(address _addr),删除 _addr 存储在 balances 中的余额,该函数必须是 external 的。

# 三、解答代码

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

contract MappingBasic {
    // Mapping from address to uint used to store balance of addresses
    mapping(address => uint) public balances;

    // Nested mapping from address to address to bool
    // used to store if first address is a friend of second address
    mapping(address => mapping(address => bool)) public isFriend;

    function examples() external {
        // Insert
        balances[msg.sender] = 123;
        // Read
        uint bal = balances[msg.sender];
        // Update
        balances[msg.sender] += 456;
        // Delete
        delete balances[msg.sender];

        // msg.sender is a friend of this contract
        isFriend[msg.sender][address(this)] = true;
    }

    function get(address _addr) external view returns (uint) {
        return balances[_addr];
    }

    function set(address _addr, uint _val) external {
        balances[_addr] = _val;
    }

    function remove(address _addr) external {
        delete balances[_addr];
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

# 四、参考资料

Last Updated: 2023-01-28 4:31:25