枚举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"});
}
}
博客围绕区块链展开,介绍了枚举(Enums)和结构体(Structs)。枚举在不同数量时类型会有变化,在特定方法中传入值有相应规则。结构体可自定义,能存放任意类型值,还介绍了初始化结构体状态变量的两种方法。
4300

被折叠的 条评论
为什么被折叠?



