1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ちゃんと理解するSolidity (4) マッピングの活用:車の所有者とその車を管理しよう

Posted at

Solidityでのプログラミングにおいて、マッピングはキーと値のペアを管理するための重要なデータ構造です。今回は、車の所有者とその車の情報を管理するためのマッピングの使い方について解説します。
スクリーンショット 2023-07-05 午後12.35.57.png

まずは、基本的なマッピングの作成方法から見ていきましょう。以下のコードは、車の所有者を表すアドレスとその所有する車のモデルを関連付けるマッピングを作成しています。

pragma solidity ^0.8.0;

contract CarContract {
    mapping(address => string) public carOwners;
}

次に、新たな車の所有者とその車をマッピングに追加する方法を見てみましょう。addCarOwner()関数を通じて新たな車の所有者とその車をcarOwnersマッピングに追加できます。

contract CarContract {
    mapping(address => string) public carOwners;

    function addCarOwner(address _owner, string memory _car) public {
        carOwners[_owner] = _car;
    }
}

さらに、複数の車を一人の所有者が持つことができるように、マッピングの中にマッピングを格納することも可能です。これをネストされたマッピングと呼びます。以下のコードでは、ネストされたマッピングを作成しています。

contract CarContract {
    mapping(address => mapping(uint => string)) public carCollections;
}

このcarCollectionsマッピングでは、外側のマッピングのキーが車の所有者(アドレス)、内側のマッピングのキーが車のID、値が車のモデルとなります。これにより、一人の所有者が複数の車を所有することを表現できます。

新たな車をこのマッピングに追加するには、以下のようにします。

contract CarContract {
    mapping(address => mapping(uint => string)) public carCollections;

    function addCarToCollection(uint _id, string memory _car) public {
        carCollections[msg.sender][_id] = _car;
    }
}

スクリーンショット 2023-07-05 午後12.42.56.png

msg.senderってなんだっけ

msg.senderはSolidityの特殊な変数であり、現在の関数を呼び出したアドレスを表します。通常、関数を呼び出す際にトランザクションを送信したアカウントのアドレスがmsg.senderに割り当てられます。

記事のコード例では、msg.senderを使用して車の所有者を特定し、その所有者に関連する情報をマッピングに格納しています。

例えば、以下のコードを見てみましょう:

function addCarOwner(address _owner, string memory _car) public {
    carOwners[_owner] = _car;
}

この関数では、_ownerというアドレスと_carという文字列が引数として渡されます。carOwnersマッピングはaddress型のキー(車の所有者のアドレス)とstring型の値(車の情報)を持ちます。msg.senderは関数を呼び出したアドレスを表し、carOwners[msg.sender]を使って、呼び出し元のアドレスに対応する車の所有者情報を格納します。

同様に、ネストされたマッピングの例でもmsg.senderを使用しています:

function addCarToCollection(uint _id, string memory _car) public {
    carCollections[msg.sender][_id] = _car;
}

この関数では、_idという整数と_carという文字列が引数として渡されます。carCollectionsは外側のマッピングと内側のマッピングを持ち、外側のマッピングのキーは車の所有者のアドレスを表し、内側のマッピングのキーは車のIDを表します。msg.senderを使って、関数を呼び出したアドレス(車の所有者)に対応するマッピングに車の情報を格納します。

msg.senderを使用することで、トランザクションを送信したアドレスに関連するデータを正確に追跡および管理することができます。

以上が、Solidityでのマッピングの基本的な使い方です。マッピングを使うことで、複雑なデータの関連性を効率的に管理することができます。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?