# 映射

By [startha](https://paragraph.com/@starha) · 2023-09-19

---

映射Mapping
---------

在映射中，可以通过键（`Key`）来查询对应的值（`Value`）,比如：通过一个人的`id`来查询他的钱包地址。

声明映射的格式为`mapping(_KeyType => _ValueType)`，其中`_KeyType`和`_ValueType`分别是`Key`和`Value`的变量类型

        mapping(uint => address) public idToAddress; //id映射地址
        mapping(address => address) public swapPair; //币对的映射，地址到地址
    

映射的规则
-----

*   **规则1**：映射的`KeyType`只能选择solidity内置的值类型，比如`uint`,`address`等，不能用自定义的结构体。而`ValueType`可以使用自定的类型。下面的这个例子会报错，因为`_KeyType`使用了自定义类型。
    

        struct Student{
            uint256 id;
            uint256 score; 
        }
        mapping(Student => uint) public testVar;
    

*   **规则2**：映射的存储位置是`storage`，因为可以用于合约的状态变量，函数中`storage`变量，和library函数的参数。不能用于`public`函数的参数或返回结果中，因为`mapping`记录的是一种关系(key - val pair)。
    
*   **规则3**：如果映射声明为`public`，那么solidity会自动给你创建`getter`函数，可以通过`Key`来查询对应的`Value`。
    
*   **规则4**：给映射新增的键值对语法为`Var[_Key] = _Value`，其中`Var`是映射变量名，`_Key`和`_Value`d对应新增的键值对。
    

        function writeMap(uint _Key, address _Value) public {
            idToAddress[_Key] = _Value;
        }
    

映射的原来
-----

*   **原理1**：映射不存储任何（`Key`）的资讯，也没有length的资讯。
    
*   **原理2**：映射使用`keccak256(abi.encodePacked(key, slot))`当成offset存取value，其中`slot`是映射变量定义所在的插槽位置。
    
*   **原理3**：因为Ethereum会定义所有未使用的空间为0，所以赋值（`Value`）的键（`Key`）初始化都是各个type的默认值，如uint的默认值是0。

---

*Originally published on [startha](https://paragraph.com/@starha/It4mBYNJPd221XTohhQ4)*
