區塊鏈:Solidity值型別(Solidity 列舉Enums & 結構體Structs)
阿新 • • 發佈:2019-02-07
列舉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
引數的值
可以是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"});
}
}