枚舉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"});
}
}