DAY 14
0
Blockchain

開發智能合約 - 表達示與流程控制 (Day14)

輸入參數和輸出參數

``````pragma solidity ^0.4.16;

contract Simple {
function taker(uint _a, uint _b) public pure {
// ...
}
}
``````

``````pragma solidity ^0.4.16;

contract Simple {
function arithmetics(uint _a, uint _b)
public
pure
returns (uint o_sum, uint o_product)
{
o_sum = _a + _b;
o_product = _a * _b;
}
}
``````
``````pragma solidity ^0.4.16;

contract Simple {
function arithmetics(uint _a, uint _b)
public
pure
returns (uint, uint)
{
o_sum = _a + _b;
o_product = _a * _b;
return (o_sum, o_product);
}
}
``````

流程控制

if

``````uint x = 10

if(x == 10) {

} else {

}
``````

for

``````for (uint x = 0; x < 10; x++) {

}
``````

while

``````uint i = 0;

while (i < 10) {
i++;
}
``````

``````if (1) {
// ...
}
``````

函式呼叫 (Function Calls)

// TODO 添加一些解釋

``````contract Math {
function f1(uint a) returns (uint) { return f(a); }
function f2(uint a) returns (uint) { return a * a}
}
``````

``````pragma solidity ^0.4.0;

contract InfoFeed {
function info() returns (uint ret) { return 42; }
}
contract Consumer {
InfoFeed feed;

// 在呼叫外部函式時，可以指定發送的貨幣數量跟 gas
function callFeed() { feed.info.value(10).gas(800)(); }
}
``````

``````pragma solidity ^0.4.0;

contract Example {
function f(uint a, uint b, uint c) {
// ...
}
function g() {
f({c: 2, a: 3});
}
}
``````

錯誤處理 (Error handling)

require

``````require(condition,[message])
``````

``````contract Example {
function superPower() {
require(msg.sender == owner);
// ...
}
}
``````

revert

``````revert();
``````

``````contract Example {
function superPower() {
if(msg.sender != owner) {
revert();
}
}
}
``````

assert

throw

使用情境判斷

`require()` 應該是你去檢查條件的函式，`assert()` 只用在防止永遠不應該發生的情境。至於 `require()``revert()` 使用的差別，只在於你需不需要條件是判斷。