0
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 3 years have passed since last update.

[Solidity] 構造体について〜NFTに使われる!?〜

Posted at

Solidity.png

いつもはflutterを書いているのですが、ブロックチェーンに興味をもち勉強を始めました。
アウトプットのために書こうと思います。
自分用のメモにも使います。

今回は構造体についてです。
動画によると、NFTなどで使うらしいです!!これは使いこなしたいところ!

構造体を作る

Kittyという構造体3つのデータを入れることにしました。

・名前(string)
・オーナー(adreess)
・ID(uint256)

struct Kitty {
    string name;
    address owner;
    uint256 id;  
}

追加する処理

pragma solidity >= 0.4.0 < 0.8.9;

contract MyContract {

    //型として使うために、Kittyという構造体の配列(kitties)を作る
    Kitty[] kitties;

    //どのキティを見るには,loopしなければならない →遅い ->mappingを使う。
    mapping(address=>uint256[]) ownerToKitty;

    function addKitty(string memory _name, address _owner) public {
         //idを作成(最初は、0番目、次は一番目)
        uint id = kitties.length;

        //追加するキティを定義する
        Kitty memory newKitty = Kitty(_name,_owner,id);

        //追加する。
        kitties.push(newKitty);

        //mappingにも記録する必要がある。
        //onwerの配列にIDを追加してあげる。
        ownerToKitty[_owner].push(id);
    }

取得する処理

pragma solidity >= 0.4.0 < 0.8.9;

contract MyContract {

    function getKitty(address _owner) public view returns(string[] memory) {
        //猫の匹数を定義する。 → 長さを返してあげる
        uint numberOfKitties = ownerToKitty[_owner].length;

        //numberOfKittiesの大きさを持ったstringの配列ができる
        string[] memory names = new string[](numberOfKitties);

        //numberOfKittiesをLoopする
        for(uint i = 0; i < numberOfKitties; i++) {
            uint id = ownerToKitty[_owner][i];
            names[i] = (kitties[id].name);
        }
        return names;
    }
}

最後に

あれですね。理解するのが難しかったですね。記事として書くために自分も理解しようとすると時間がかかりますね。でも理解が深まるのでいい勉強になっています。まだ、これを使ってものを作れていないので楽しさがわかっていないですが、ものを作り出そうとすると楽しめると思います!

まずは基本からやっていこうと思っています。
修正点があれば、コメントください!!

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