以下介紹比較常用的變數
int // 有符號整數 (+ -)
uint // 無符號整數 (+)
// 可能大家還會看到 uint ~ uint256 但是盡量不要超過長度會有溢位攻擊
// 當然**OpenZeppelin** 已經解決此問題
// 舉例: uint token = 10 ** 2;
補充 [溢位攻擊](<https://www.jianshu.com/p/6e0fbac0918a>)
bool b = true; // true, false
// 舉例:是否存款 depo = true
// 是否開盲盒 openbox = false
string tokenName = 'SToken'; // 命名
address owner = 0xbFc14BC72590eB6G3AF0873d3401Fac602942Ad3;
// 這是智能合約特殊的變數一定要了解
Struct
Solidity 也支援比較複雜的資料格式,可以用 Struct 來定義一組變項的集合.
struct Person{
string name;
uint dna;
}
// 也可以作成組合式的
struct IpfsHash {
bytes32 hash;
uint hashSize;
}
struct Member {
IpfsHash ipfsHash;
}
// 通常都是會用在資料整理 舉例: UserInfo、PoolInfo ...等。
uint[2] fixedArray; //長度為 2 的 int array
string[5] stringArray; //長度為 5 的 string Array
uint[] dynamicArray; //動態 Array
/* 補充操作
// push (增加)、pop (最後一個刪除)、length (長度)、delete Array[index] 指定刪除
*/
自己比較常用到 Struct + Array
struct Person{
string name;
uint age;
}
Person[] public people;
people.push(Person("0xRory",28);
補充:
修飾詞:
storage存儲
storage的修飾詞,數據將永遠存在於區塊鏈上。
memory內存 memory存儲位置同我們普通程序的內存類似,即分配,即使用,動態分配,越過作用域即不可被訪問,等待被回收。
總結¶ 強制指定的數據位置: • 外部函數的參數(不包括返回參數 • 狀態變量: storage
默認數據位置: • 函數參數(包括返回參數): memory • 所有其它局部變量: storage
有任何問題可反饋: [email protected]