メインコンテンツまでスキップ

Enum,Struct

Enum,Structについて学習します

enum

列挙型

特定の状態やオプションの一覧を視覚的に表現、コードの意味を明確にできる

enumは整数として取り扱うこともできる

デフォルトは定義の最初の値になる

contract EnumSample {
enum Status { Pending, Approved, Rejected }

// Default value is Pending
Status currentStatus;

function approve() {
currentStatus = Status.Approved;
}

function approve2() {
// This is true, means Pending
if(uint256(currentStatus) == 0) {
currentStatus = Status.Approved;
}
}

function deleteStatus() {
currentStatus will be Pending;
delete currentStatus;
}
}

struct

複数の変数をグループ化できるカスタム定義の型

定義

struct identifier {
Type value-identifier;
}

で定義する

contract StructSample {
struct testStruct {
uint a;
bool b;
}
}

宣言

3つの方法で宣言できる

  • 関数のような宣言
  • mappingのような宣言
  • 初期値なし(各メンバはデフォルト値)の宣言

ただしメンバにmappingがある場合は初期値なしでしか宣言できない

ローカル変数として宣言する際にはmemory修飾子を付ける必要がある

contract Struct {
struct Sample {
uint a;
bool b;
}

function define() {
// function method
Sample memory x = Sample(1,true);

// mapping method
Sample memory y = Sample({a: 2,b: true});

// empty method
Sample memory z;
}
}

ストレージ変数を関数内で操作する場合、storage修飾子を付けることで宣言できる

contract Struct {
struct Sample {
uint a;
bool b;
}

Sample storageSample;

function define() {
// function method
Sample storage tmp = storageSample;
}
}

参照・代入

structの変数名.メンバ名でメンバにアクセスできる

contract Struct {
struct Sample {
uint a;
bool b;
}

function reference() {
Sample memory x = Sample(1,true);

// y will be 1
uint y = x.a;
}

function substitution() {
Sample memory x = Sample(1,true);

// x.a will be 2
x.a = 2;
}
}

Reference