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

Data Location

StorageとMemory,Calldataについて学習します

Storage

ブロックチェーン上に保存される永続的な領域

変数はコントラクト中、関数外に宣言する

contract StorageSample {
uint count;

// Count variable keeps increasing with each function call
function add(){
count += 1;
}
}

Memory

関数の実行中のみ存在する一時的な領域

contract Memory {
// No matter how many times you call the function, count will always be 1.
function add() {
uint count;
count += 1;
}
}

storage変数をmemory変数に代入した場合、基本的にmemory変数として取り扱われる

array、struct、mappingに関してはstorage修飾子をつけることでstorageに代入することができる

contract Memory {
uint count;
uint[] array;

// count remains at 0
function storeMemory() {
uint memoryCount = count;
memoryCount = 1;
}

// 1 is inserted in array
function storeStorage() {
uint[] storage copy = array;
copy.push(1);
}
}

Calldata

関数の実行中のみ存在する一時的な領域

関数の引数にのみ修飾可能で、変更不可能(Memoryは変更可能)

contract Calldata {
function calldataParam(string calldata a) {
// Changes cause error
a = "change statement";
}

function memoryParam(string memory a) {
// safe
a = "change statement";
}
}

Reference