在 Solidity 中使用索引时是否需要特定条件?

Should I require a specific condition when working with indexes in Solidity?

pragma solidity ^0.4.0;

contract A{
    byte[10] arr;

    function setElement(uint index, byte value) public {
        require(index >= 0 && index < arr.length); //Should I leave it as is?
        arr[index] = value;
    }

    function getElement(uint index) view public returns (byte) {
        require(index >= 0 && index < arr.length); //Or not?
        return arr[index];
    }
}

据我所知,在以下情况下会生成断言式异常,而不仅仅是:

但是每次都要检查条件吗?

另外我想把剩余的gas退还给executor

您正在正确使用它。 require 旨在用于检查输入参数,而 assert 用于验证合约的内部结构(主要用于测试目的)。如果 require 条件失败,剩余的气体将被退还。

来自Solidity documentation

The convenience functions assert and require can be used to check for conditions and throw an exception if the condition is not met. The assert function should only be used to test for internal errors, and to check invariants. The require function should be used to ensure valid conditions, such as inputs, or contract state variables are met, or to validate return values from calls to external contracts.