LoginSignup
12
5

More than 5 years have passed since last update.

SolidityのMapping nullの扱いについて

Last updated at Posted at 2018-02-15

問題

Solidityでnullは使えないらしい。
mappingの「指定されたkeyに対して、何も登録されていない」や「key自体が存在しない」という条件を作る時に困った。

解決方法

状態変数の初期値を利用する。
初期値は型によって異なる。それぞれ、以下のようになっている。

初期値
uint 0
string ""
address 0x0
bytes 0x

例えば、uint型の状態変数を使うのであれば、
uint型の変数==0
を確認すれば良い。

以下、試しにuint型の状態変数==0 を使って、mappingが空の時とそうじゃないときで分岐を作ってみる。

zombie.sol

pragma solidity ^0.4.13;

contract ZombieContract{


    struct Zombie {
        uint zombieId;
        string zombieName;
    }

    mapping (address => Zombie) addressToZombie;


    function setZombie(uint _zombieId, string _zombieName) {
        addressToZombie[msg.sender].zombieId = _zombieId;
        addressToZombie[msg.sender].zombieName = _zombieName;
    }


    function getZombie() constant returns (uint, string) {
        //mappingに登録されている場合
        if (addressToZombie[msg.sender].zombieId != 0){
            return (addressToZombie[msg.sender].zombieId, addressToZombie[msg.sender].zombieName);
        } else{
               //mappingが空の場合
            return(111, "you don have Zombie");
        }

    }

}

実行結果

setZomibe(1, "myZombie")を実行後にgetZombie()を実行した場合

{
    "0": "uint256: 1",
    "1": "string: myZombie"
}

mappingが空の時に、getZombie()を実行した場合

{
    "0": "uint256: 111",
    "1": "string: you don have Zombie"
}

条件分岐できた。

参考
https://forum.ethereum.org/discussion/7313/check-null-values-in-map-solidity

12
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
5