solidity语言3

#函数类型(function type)
function (<parameter types>) {internal|external(public)} [pure|constant|view|payable] [returns (<return types>)]

有内部类型(internal)与外部(external)两种类型,如不提示关键字,默认是 internal。内部函数仅当前合约可以调用,外部函数由地址和函数签名组成,它们能传递和调用后返回结果。

合约中访问函数有2种方法:  直接用函数名,如f;或者 this.f
此外,外部函数有特别的成员属性seletor,返回 ABI function selector
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); //

    function buySomething() {
        oracle.query("USD", this.oracleResponse);
    }

    function oracleResponse(bytes response) public {
        require(msg.sender == address(oracle));
        // Use the data
    }
}
posted on 2018-02-27 16:36 北京涛子 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/liujitao79/p/8479650.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值