區塊鏈:Solidity值類型(Solidity 枚舉Enums & 結構體Structs)

枚舉Enums

案例

pragma solidity ^0.4.4;

contract test {
    enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }
    ActionChoices _choice;
    ActionChoices constant defaultChoice = ActionChoices.GoStraight;

    function setGoStraight(ActionChoices choice) public {
        _choice = choice;
    }

    function getChoice() constant public returns (ActionChoices) {
        return _choice;
    }

    function getDefaultChoice() pure public returns (uint) {
        return uint(defaultChoice);
    }
}

ActionChoices就是一個自定義的整型,當枚舉數不夠多時,它默認的類型爲uint8,當枚舉數足夠多時,它會自動變成uint16,下面的GoLeft == 0,GoRight == 1, GoStraight == 2, SitStill == 3。在setGoStraight方法中,我們傳入的參數的值可以是0 - 3當傳入的值超出這個範圍時,就會中斷報錯

結構體Structs

自定義結構體

pragma solidity ^0.4.4;

contract Students {

    struct Person {
        uint age;
        uint stuID;
        string name;
    }

}

Person就是我們自定義的一個新的結構體類型,結構體裏面可以存放任意類型的值。

初始化一個結構體

初始化一個storage類型的狀態變量。

  • 方法一
pragma solidity ^0.4.4;

contract Students {

    struct Person {
        uint age;
        uint stuID;
        string name;
    }

    Person _person = Person(18,101,"wt");

}
  • 方法二
pragma solidity ^0.4.4;

contract Students {

    struct Person {
        uint age;
        uint stuID;
        string name;
    }
    Person _person = Person({age:18,stuID:101,name:"wt"});
}

初始化一個memory類型的變量。

pragma solidity ^0.4.4;

contract Students {

    struct Person {
        uint age;
        uint stuID;
        string name;
    }

    function personInit() {

        Person memory person = Person({age:18,stuID:101,name:"liyuechun"});
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章