The keymapping in the computer program, Solidity judges whether the same key already exists in the mapping

When writing smart contracts, the mapping linked list is often used to store data, so how to judge whether the same key already exists in the mapping?

Methods as below:

struct Entry {

bytes32 id;

uint balance;

bool used;

}

mapping (address => Entry) public collection;

function addEntry(bytes32 _id, uint _balance) public {

require(!collection[msg.sender].used);

collection[msg.sender] = Entry(_id, _balance, true);

}

In the example, the value of the mapping stores a structure, the used is a bool variable, and the default is false. If you try to get a non-existent key from the mapping, the used of the obtained structure must be the default value of false, so it can be used It determines whether the key exists. Of course, when adding a structure to the mapping, used must be set to true.

When the value of the mapping stores the address, the following methods can be used:

mapping (bytes32 => address) public users;

function addUser(bytes32 id) public {

require(users[id] != address(0));

users[id] = msg.sender;

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324209474&siteId=291194637
Recommended