智能合约语言 Solidity 教程系列3 - 函数类型

Solidity 教程系列第三篇 - Solidity 函数类型介绍。
Solidity 系列完整的文章列表请查看分类-Solidity

写在前面

Solidity 是以太坊智能合约编程语言，阅读本文前，你应该对以太坊、智能合约有所了解，如果你还不了解，建议你先看以太坊是什么

函数类型（Function Types）

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

internal访问形式为f, external访问形式为this.f

成员: 属性 selector

public (或 external) 函数有一个特殊的成员selector, 它对应一个ABI 函数选择器。

``````pragma solidity ^0.4.16;

contract Selector {
function f() public view returns (bytes4) {
return this.f.selector;
}
}``````

``````pragma solidity ^0.4.16;

library ArrayUtils {
// internal functions can be used in internal library functions because
// they will be part of the same code context
function map(uint[] memory self, function (uint) pure returns (uint) f)
internal
pure
returns (uint[] memory r)
{
r = new uint[](self.length);
for (uint i = 0; i < self.length; i++) {
r[i] = f(self[i]);
}
}
function reduce(
uint[] memory self,
function (uint, uint) pure returns (uint) f
)
internal
pure
returns (uint r)
{
r = self[0];
for (uint i = 1; i < self.length; i++) {
r = f(r, self[i]);
}
}
function range(uint length) internal pure returns (uint[] memory r) {
r = new uint[](length);
for (uint i = 0; i < r.length; i++) {
r[i] = i;
}
}
}

contract Pyramid {
using ArrayUtils for *;
function pyramid(uint l) public pure returns (uint) {
return ArrayUtils.range(l).map(square).reduce(sum);
}
function square(uint x) internal pure returns (uint) {
return x * x;
}
function sum(uint x, uint y) internal pure returns (uint) {
return x + y;
}
}``````

``````pragma solidity ^0.4.11;

contract Oracle {
struct Request {
bytes data;
function(bytes memory) external callback;
}
Request[] requests;
event NewRequest(uint);
function query(bytes data, function(bytes memory) external callback) public {
requests.push(Request(data, callback));
NewRequest(requests.length - 1);
}
function reply(uint requestID, bytes response) public {
// Here goes the check that the reply comes from a trusted source
requests[requestID].callback(response);
}
}

contract OracleUser {
Oracle constant oracle = Oracle(0x1234567); // known contract
oracle.query("USD", this.oracleResponse);
}
function oracleResponse(bytes response) public {
// Use the data
}
}
``````

函数可见性分析

• public - 任意访问
• private - 仅当前合约内
• internal - 仅当前合约及所继承的合约
• external - 仅外部访问（在内部也只能用外部访问方式访问）

参考文档

Solidity官方文档-类型

☛ 我的知识星球为各位解答区块链技术问题，欢迎加入讨论。

☛ 关注公众号“深入浅出区块链技术”第一时间获取区块链技术信息。