Smart Contract 開發實戰(二) — functions
Published in
3 min readJun 24, 2018
這一系列主要紀錄學習開發 Smart Contract 的過程…
宣告 function
function doAbaby(string _name, uint _mother, uint _father) {
}
宣告 function 的方式和 js 很像,用 function 關鍵字當開頭,後面接function name,括號中放要傳入的參數型別和名稱.這邊用 _ 當開頭是為了與一般 global 變數做區別.
Combine them together
在上一篇有提到 Array 和 Struct,但是沒提到怎麼使用:
如果要宣告一個新的 Struct 物件:
Person baby = Person('Bryan', 5566);
如果要在 people 這個 array 上新增元素:
people.push(baby);
把這兩個東西和 Function 結合:
function doABaby(string _name, uint _mother, uint _father) { Person baby = Person(_name, _mother * _father % 10);
people.push(baby);}
Private/ Public
在宣告 function 時,可以定義這是個 Private 還是 Public (預設).
- Private:表示這個函式只能在合約內部呼叫.
- Public:表示任何人都可以看到並且呼叫這個函式.
選告的方式很簡單,就在函式後加上 public/private 就好.
uint[] numbers;
function _addToArray(uint _number) private { numbers.push(_number); }
回傳值
如果要得到函式的結果,需要加上
- 回傳值的型別
- 在函式最後加上 return .
function doABaby(string _name, uint _mother, uint _father) public returns (uint) {
uint _dna = _mother * _father % 10 ;
Person baby = Person(_name, _dna);
people.push(baby);
return _dna;}
其他函式屬性
函式在宣告上,還可以根據有沒有修改到 state 以及有沒有讀取內部變數來區分:
view
如果這個函式沒有修改 state 可以加上
string hello = 'Hello'
function hi() view returns (string) { return hello;}
pure
如果函式沒有用到內部變數可以用(類似 python 的 @staticmethod
)
function _add(uint _a, uint _b) private pure returns (uint){ return _a + _b;}