【问题标题】:Possible to cast uint256[100] memory to uint256[10] memory?可以将 uint256[100] 内存转换为 uint256[10] 内存吗?
【发布时间】:2021-08-24 00:38:08
【问题描述】:

是否可以让 getFirst10() 工作?似乎不可能将 uint256[100] 内存转换为 uint256[10] 内存。

contract Test {
  uint256[100] private foo;

  function get() external view returns (uint256[100] memory) {
    return foo;               // Works
  }
  function getFirst10() external view returns (uint256[10] memory) {
    return uint256[10](foo);  // Doesn't compile
  }
}

我得到的最接近的是上面的尝试,但它失败并出现错误:Error: Explicit type conversion not allowed from "uint256[100] storage ref" to "uint256[10] storage pointer"

我想要做的是有一个函数返回一个大的 uint256[] 存储数组的子切片。有没有办法做到这一点?我是否必须改为返回 calldata 并复制每个元素?

【问题讨论】:

  • 为什么要这样做? uint256[100] 内存转 uint256[10] 内存
  • 我想在存储上返回一片 uint256[]。我只需要数据的一个子集。
  • 切片语法不适用于存储阵列。我想知道是否还有其他一些强制转换语法,但我认为解决方案只是将元素循环并复制到函数中的新静态内存数组中。

标签: arrays solidity evm


【解决方案1】:

我认为正确的解决方案是创建一个所需固定大小的函数本地内存数组,并复制元素。在阅读了有关“存储”与“内存”的更多信息之后,我猜 EVM 在“相同大小”的情况下会为您做这件事,但除此之外似乎没有任何强制转换语法来避免编写循环自己。我不认为会影响性能或 gas 成本,但可能是错误的。

  function getFirst10() external view returns (uint256[10] memory) {
    uint256[10] chunk;
    for (uint32 j = 0; j < 10; j++) {
      chunk[j] = foo[j];
    }
    return chunk;
  }

【讨论】:

    猜你喜欢
    • 2018-08-20
    • 2022-11-22
    • 2022-08-13
    • 2017-09-05
    • 1970-01-01
    • 2022-08-06
    • 2022-01-05
    • 1970-01-01
    • 2020-02-04
    相关资源
    最近更新 更多