-
-
Save DerayGa/f6793e4438cbe319b96762d59e9bd0e3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| pragma solidity ^0.4.2; | |
| library Set { | |
| // library 不能真的有狀態變數,但呼叫 library 的合約可以擁有 (請見下方 contract) | |
| struct Data { mapping(uint => bool) flags; } | |
| // 加上 storage 修飾字之後,self 就會指向呼叫 library 的合約的某個狀態變數 | |
| // 此為 library 特有的功能 | |
| function insert(Data storage self, uint value) returns (bool) { | |
| if (self.flags[value]) | |
| return false; // value already there | |
| self.flags[value] = true; | |
| return true; | |
| } | |
| function remove(Data storage self, uint value) returns (bool) { | |
| if (!self.flags[value]) | |
| return false; // not there | |
| self.flags[value] = false; | |
| return true; | |
| } | |
| function contains(Data storage self, uint value) returns (bool) { | |
| return self.flags[value]; | |
| } | |
| } | |
| contract C { | |
| // 建立 library 裡面需要的實體個體 Data (Data 在這是一個變數) | |
| Set.Data knownValues; | |
| function register(uint value) { | |
| // 呼叫 library 中的方法 | |
| // 假如今天 library 裡面有 this,那麼就是指 C 這個合約 | |
| if (!Set.insert(knownValues, value)) | |
| throw; | |
| } | |
| // 我們也可以直接 knownValues.flags 來存取實體 Data 結構中的 flags | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment