📜 [專欄新文章] Solidity Weekly #11
✍️ mingderwang
📥 歡迎投稿: https://medium.com/taipei-ethereum-meetup #徵技術分享文 #使用心得 #教學文 #medium
pure 跟 view 怎麼用?
在 Solidity 0.4.16 (含)之前,modifier constant 表示該 function 不會動到合約的 state (狀態), 例如:
string greeting;
function SayHello() public constant returns(string says) { return greeting;}
greeting 在 constructor 或其他地方, 已經有值,在這 SayHello() function 裡並沒有更動到 greeting 的值 (也就是合約的狀態)。
更正確的講,如果一個 function 不會改變到合約的 state,就可以加 modifier constant 在 returns 前面,因此在 web3.js 就可以用 call() 來呼叫該 function, 而不需要用 sendTransaction() 來呼叫。
到了 solc 0.4.17, 更把 constant 細分為 view 或 pure 兩種,只是程度上的不同。
view 一般來說,就用來取代 constant, 跟 compiler 説,該 function 不會對 storage state 有任何變動。(但會進行讀取, 所以 constant 改名為 view,更為恰當)
string greeting;
function SayHello() public view returns(string says) { return greeting;}
pure 定義該 function 連讀 storage state 都沒有。有人舉了一個誇張的例子如下:(它跟合約的所有 states 都無關, 可以加 modifier pure)
function returnTrue() public pure returns(bool response) { return true;}
links 分享;
Plasma Cash Simple Spec — (Karl Floersch)
Plasma Cash Initial Release — Plasma-Backed NFTs Now Available on Loom Network Sidechains — (Matthew Campbell)
https://github.com/loomnetwork/plasma-cash
https://github.com/omisego/plasma-cash
後記;
那麼有用 view 或 pure 有什麼好處?當然有了,以後 solc 最佳化, 可以因沒有 transaction, 而不需花 gas。現在這類的 function 也不必花時間到 network 去做確認造成 delay,也可以靠 compiler 檢查,避免 state 被意外修改。所以該加 view 或 pure 就要加。
*view 和 pure 取代 constant 開始於 solidity ^0.4.17
Solidity Weekly #11 was originally published in Taipei Ethereum Meetup on Medium, where people are continuing the conversation by highlighting and responding to this story.
👏 歡迎轉載分享鼓掌
「js return string」的推薦目錄:
- 關於js return string 在 Taipei Ethereum Meetup Facebook 的精選貼文
- 關於js return string 在 Returning a string in Javascript - Stack Overflow 的評價
- 關於js return string 在 Returning Multiple Values from a Function - JavaScript Tutorial 的評價
- 關於js return string 在 jprichardson/string.js: Extra JavaScript string methods. - GitHub 的評價
- 關於js return string 在 Why don't I get the String value returned from apex in js in the ... 的評價
- 關於js return string 在 JsString in js_sys - Rust 的評價
js return string 在 Returning Multiple Values from a Function - JavaScript Tutorial 的推薦與評價
Summary · JavaScript doesn't support functions that return multiple values. However, you can wrap multiple values into an array or an object and return the array ... ... <看更多>
js return string 在 jprichardson/string.js: Extra JavaScript string methods. - GitHub 的推薦與評價
The only difference is that the imported methods return string.js objects instead of native JavaScript strings. The one exception to this is the method ... ... <看更多>
js return string 在 Returning a string in Javascript - Stack Overflow 的推薦與評價
... <看更多>
相關內容