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

• Tiny熊
• 更新于 2017-12-12 15:25
• 阅读 38646

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

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

## 写在前面

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

## 函数类型（Function Types）

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

### 成员: 属性 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 &lt; 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 &lt; 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 &lt; 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
function buySomething() {
oracle.query("USD", this.oracleResponse);
}
function oracleResponse(bytes response) public {
require(msg.sender == address(oracle));
// Use the data
}
}
``````

## 函数可见性分析

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

## 参考文档

Solidity官方文档-类型

``````pragma solidity^0.4.18;

contract Test {
uint[10] x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

function test(uint[10] a) public returns (uint){
return a[9]*2;
}

function test2(uint[10] a) external returns (uint){
return a[9]*2;
}

function calltest() {
test(x);
}

function calltest2() {
this.test2(x);
//test2(x);  //不能在内部调用一个外部函数，会报编译错误。
}

}``````

-->

Tiny熊
0xD682...E8AB