1. 程式人生 > >區塊鏈學堂(24):Struct型別

區塊鏈學堂(24):Struct型別

Struct型別定義

例如定義一個struct型別的Person

  struct Person {
    string name;
    uint sexy; //0: 男性;1:女性;
    uint age;
    string mobile;
  }

建立一個Struct的Demo合約

  • Step 1: 撰寫最基本的合約
pragma solidity 0.4.10;
contract DemoTypes9 {
  struct Person {
    string name;
    uint sexy; //0: 男性;1:女性;
    uint age;
    string mobile;
  }


  Person[] public PersonList;
}

最初的合約只定義了struct person型別,以及一個數組Person[] PersonList

  • Step 2: 給建構函式中新增初始化程式碼
    function DemoTypes9() {
      /*陣列型別新增元素方式1*/
      uint id = PersonList.length++;
      Person p  = PersonList[id];
      p.name = "阿三";
      p.sexy = 0;
      p.age = 20;
      p.mobile = "13918802350";
    }
    
Step 1-2後,完整程式碼如下:
pragma solidity 0.4.10;
/*演示一下結構,如何和陣列型別結合,一起使用;*/
contract DemoTypes9 {
  struct Person {
    string name;
    uint sexy; //0: 男性;1:女性;
    uint age;
    string mobile;
  }


  Person[] public PersonList;
  function DemoTypes9() {
    /*陣列型別新增元素方式1*/
    uint id = PersonList.length++;
    Person p  = PersonList[id];
    p.name = "阿三";
    p.sexy = 0;
    p.age = 20;
    p.mobile = "13918802350";
  }
}
以上程式碼在Browser-solidity中的執行結果如下圖所示:

  • Step 3: 新增一個AddPerson function, 使用之前的陣列型別使用過的push方法
  function AddPerson (string _name, uint _sexy, uint _age, string _mobile) {
    /*陣列型別新增元素方式2*/
    Person memory tmp;
    tmp.name = _name;
    tmp.sexy = _sexy;
    tmp.age = _age;
    tmp.mobile = _mobile;

    PersonList.push(tmp);
  }

Browser-solidity的執行情況如下:

  • Step4: 上面的AddPerson() 有點長,下面有一個更簡單的方法 AddPerson2()
  function AddPerson2 (string _name, uint _sexy, uint _age, string _mobile) {
    /*陣列型別新增元素方式3*/
    uint id = PersonList.length++;
    PersonList[id] = Person({name: _name, sexy: _sexy, age: _age, mobile: _mobile});
  }

AddPerson2() 的方法簡潔了很多
Browser-solidity的執行情況如下

完整程式碼在下面:

pragma solidity 0.4.10;
/*演示一下結構,如何和陣列型別結合,一起使用;*/
contract DemoTypes9 {
  struct Person {
    string name;
    uint sexy; //0: 男性;1:女性;
    uint age;
    string mobile;
  }


  Person[] public PersonList;
  function DemoTypes9() {
    /*陣列型別新增元素方式1*/
    uint id = PersonList.length++;
    Person p  = PersonList[id];
    p.name = "阿三";
    p.sexy = 0;
    p.age = 20;
    p.mobile = "13918802350";
  }

  function AddPerson (string _name, uint _sexy, uint _age, string _mobile) {
    /*陣列型別新增元素方式2*/
    Person memory tmp;
    tmp.name = _name;
    tmp.sexy = _sexy;
    tmp.age = _age;
    tmp.mobile = _mobile;

    PersonList.push(tmp);
  }

  function AddPerson2 (string _name, uint _sexy, uint _age, string _mobile) {
    /*陣列型別新增元素方式3*/
    uint id = PersonList.length++;
    PersonList[id] = Person({name: _name, sexy: _sexy, age: _age, mobile: _mobile});
    }
}

原文:http://www.ethchinese.com/?p=1047

QQ群:559649971 (區塊鏈學堂粉絲群)
個人微信:steven_k_colin

獲取最新區塊鏈諮詢,請關注《以太中文網》微信公眾號:以太中文網