LoginSignup
44
25

More than 5 years have passed since last update.

Solidity 言語における詰まりどころメモ

Posted at

Ethereum のスマートコントラクト記述言語 Solidity は、他のプログラミング言語と比べると言語仕様が少し特殊なところがあります。
Solidity を書いていて、詰まったり躓いたりしたポイントをメモしていきたいと思います。

なお、使用しているのは Solidity 0.4.18 です。もし間違っている点がありましたらぜひ教えてください。

変数の値が存在しないこと(NULL)を判定したい

Solidity に NULL はありません。
代替手段として、デフォルトの初期値であるかどうかで判定することができます。

Solidity で宣言されたすべての変数には、デフォルトの初期値が設定されています。
また、配列の場合は、length が0であるかどうかで判定できます。

type initial default value
bool false
uint 0
int 0
fixed 0.0
string ""
address 0x0

Struct を返却したい

https://ethereum.stackexchange.com/questions/36229/invalid-solidity-type-tuple
https://ethereum.stackexchange.com/questions/3609/returning-a-struct-and-reading-via-web3

Struct は返り値として受け取ることができません。
代替手段として、Struct をフィールドを別々の戻り値として返却する方法があります。

contract Sample {
    struct User {
        uint userId;
        string name;
    }
    User[] public users;

    function addUser(uint _userId, string _name) public returns (uint) {
        return users.push(User(_userId, _name)) - 1;
    }

    function getUser(uint _index) public view returns (uint, string) {
        return (users[_index].userId, users[_index].name);
    }
}

なお、内部呼び出しの関数であれば返り値として構造体を受け取ることはできるようです。

Array から一部削除したい

delete オペレータを使用して削除できます。

contract Sample {
    uint[] public array = [1, 2, 3, 4, 5];
    function remove(uint _index) public {
        delete array[_index];
    }
}

String の Array を返却したい

String の Array はまだ返却できません。

Solidity では、多次元配列(厳密には、動的配列の動的配列)が未実装のようです。
String は動的配列そのものなので、返却しようとすると UnimplementedFeatureError: Nested dynamic arrays not implemented here エラーが出ます。

Attempting to run transaction which calls a contract function, but recipient address is not a contract address が発生する

./build/contracts を削除します。
言語仕様とは少し異なるところですが、このエラーが突然発生すると焦るので書き残しておきます。

44
25
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
44
25