solidity智能合约[26]-mapping

mapping

mapping是一张表,存储key-value对。更准确的说,mapping是一张hash映射表,内部并没有存储真实的key值。

1
2
3
Mappings can be seen as hashtables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros: a type’s default value. The similarity ends here, though: The key data is not actually stored in a mapping, only its keccak256 hash used to look up the value.

Because of this, mappings do not have a length or a concept of a key or value being “set”.

mapping用例

下面的案例模拟了一个登陆网站,将地址与id绑定在一起。id又与姓名绑定在一起。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
pragma solidity ^0.4.23;
contract mappingTest{

uint id = 0;

mapping(address =>uint) idmap;//将地址与id绑定在一起
mapping(uint =>string) namemap;//id又与姓名绑定在一起。

//注册
function regist(string name) public{
address acount = msg.sender;
id++;
idmap[acount] = id;
namemap[id] = name;
}
//根据地址获取id
function getIdByAddress(address _address) public view returns(uint){
return idmap[_address];
}
//根据id获取名字
function getNameByID(uint _id) public view returns(string){
return namemap[_id];
}
}