DAY 13
0
Blockchain

## 開發智能合約 - Solidity 型別 (Day13)

#### 布林 (Boolean)

``````bool valid = true;
bool valid = false;
``````

#### 整數 (Integer)

int

``````int8 amount = 100; // -127 ~ 127
int256 amount = 100;
int amount = 100; // 是 int256 的別名
``````

uint

• 無符號整數型別
• 常用來表示貨幣數量和時間戳 (timestamp)
• 值的範圍是 0 ~ 2 的 n 次方，以 uint8 來說 2^8-1。
``````uint8 amount = 100; // 0 ~ 255
uint256 amount = 100;
uint amount = 100; // 是 uint256 的別名
``````

Solidity 沒有 double 和 float

``````function case1() returns (uint) {
uint8 x = 255;
uint8 y = 1;
return a + b
}

Assert.equal(case1(), 0);
``````

``````function case2() returns (uint) {
uint8 x = 0;
uint8 y = 1;
return a - b
}

Assert.equal(case2(), 255);
``````

``````address [public] addr;
``````

``````address addr;

// 轉帳，交易發生錯誤時拋出 error
// 轉帳，交易發生回傳 bool 值
``````

#### 位元組 (Bytes)

bytes1, bytes2, bytes3...bytes32

``````bytes [storage|memory] [public] name;
``````

``````// 宣告
bytes public myBytes;
// 取得長度
myBytes.length;
// 添加內容
myBytes.push(hex"ff");
``````

`byte``bytes1` 的別名

#### 字串 (String)

`UTF8` 編碼，動態分配大小。

``````string [storage|memory] [public] nickName;
``````

``````// 宣告
string nickName = "alincode";

// 刪除值
delete nickName;
``````

Solidity 無法直接進行字串比對，可以用 `sha3` 來比對。

``````if (sha3(name1) == sha3(name2))
``````

#### 列舉 (Enum)

``````enum State { Start, Pending, End }
State state = State.Start;

function getState() view returns (uint) {
return uint(state);
}
``````

#### Arrays

``````type[size] [memory|storage] [public] name;
``````

``````// 固定陣列
int[5] myArray;
// 動態陣列
int[] anotherArray; - dynamic array
// 宣告為記憶體陣列
uint[] memory myArray = new uint[](5);
``````

``````// 刪除陣列內容
delete myArray;
// 取得陣列長度
myArray.length;
// 新增一個元素至陣列
myArray.push(1);
// 取得指定位址元素的值
myArray[3];
// 設定指定位址元素的值
myArray[3] = 8;
``````

``````address[] funderIndexs;

function getFunders() public view returns (string[], uint[]) {
string[] memory names = new string[](funderIndexs.length);
uint[] memory amounts = new uint[](funderIndexs.length);
// 略...
return (names, amounts);
}

function addFunder() public {
funderIndexs.push(msg.sender);
}
``````

#### 結構 (Struct)

``````struct name { [member; ... ] };
``````

``````// 宣告
struct Person {
string name;
int height;
}

// 實例化
Person customer;

// 設定值
customer = Person({ name: 'alincode', age: 160 });
customer2 = Person('alincode', 160);
customer.name;
customer.height = 160;
``````

``````mapping (address => Funder) funders;

struct Funder {
uint amount;
uint createdAt;
string name;
}

function fund(string _name) public payable {
funders[msg.sender] = Funder(msg.sender, msg.value, now, _name);
}
``````

payable 是一種函式的修飾標記，會在函式的篇幅在做說明。

### 值型別 (Value Type)

• 布林
• 整數
• bytes
• 字串
• enum

``````function (<parameter types>) {internal|external} [pure|constant|view|payable] [returns (<return types>)]
``````

• Array
• Struct