数组切片

2022-05-12 17:01 更新

数组切片是数组连续部分的视图。它们写成x[start:end], wherestart和 end是导致 uint256 类型(或隐式转换为它)的表达式。切片的第x[start]一个元素是 ,最后一个元素是。x[end - 1]

如果start大于end或end大于数组的长度,则抛出异常。

两者start和end都是可选的:默认start为数组的长度。0end

数组切片没有任何成员。它们可以隐式转换为其基础类型的数组并支持索引访问。索引访问在底层数组中不是绝对的,而是相对于切片的开头。

数组切片没有类型名称,这意味着没有变量可以将数组切片作为类型,它们只存在于中间表达式中。

笔记

到目前为止,数组切片仅针对 calldata 数组实现。

数组切片对于 ABI 解码函数参数中传递的辅助数据很有用:

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.8.5 <0.9.0;
contract Proxy {
    /// @dev Address of the client contract managed by proxy i.e., this contract
    address client;

    constructor(address client_) {
        client = client_;
    }

    /// Forward call to "setOwner(address)" that is implemented by client
    /// after doing basic validation on the address argument.
    function forward(bytes calldata payload) external {
        bytes4 sig = bytes4(payload[:4]);
        // Due to truncating behaviour, bytes4(payload) performs identically.
        // bytes4 sig = bytes4(payload);
        if (sig == bytes4(keccak256("setOwner(address)"))) {
            address owner = abi.decode(payload[4:], (address));
            require(owner != address(0), "Address of owner cannot be zero.");
        }
        (bool status,) = client.delegatecall(payload);
        require(status, "Forwarded call failed.");
    }
}


以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号