SOLIDITY:返回没有推送的经过筛选的结构数组。 [英] Solidity: Returns filtered array of structs without 'push'

查看:0
本文介绍了SOLIDITY:返回没有推送的经过筛选的结构数组。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有结构数组的合同:

pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;

contract Tickets {
  struct Ticket {
    uint id;
    int val;
  }

  Ticket[] tickets;

  function addTicket(uint id, int val) public returns(bool success) {
    Ticket memory newTicket;
    newTicket.id = id;
    newTicket.val = val;
    tickets.push(newTicket);

    return true;
  }

  function getTicket(uint id) public view returns(Ticket memory) {
    uint index;

    for(uint i = 0; i<tickets.length; i++){
      if (tickets[i].id == id) {
        index = i;
        break;
      }
    }

    Ticket memory t = tickets[index];

    return t;
  }

  function findTickets(int val) public view returns(Ticket[] memory) {
    Ticket[] memory result;

    for(uint i = 0; i<tickets.length; i++){
      if (tickets[i].val == val) {
        result.push(tickets[i]); // HERE IS THE ERROR
      }
    }

    return result;
  }
}

我需要返回一个筛选依据val数组,但当我编译此代码时:result.push(tickets[i].id);它抛出以下错误:

TypeError: Member "push" is not available in struct Tickets.Ticket memory[] memory outside of storage.

如何实现筛选器而不使用push

推荐答案

返回结构的动态长度数组在坚固性方面仍然有点棘手(即使在当前的0.8版本中也是如此)。因此,我做了一些变通方法,使其即使在0.6版本中也能正常工作。

  1. 确定结果计数,您将在步骤2中使用它。
  2. 创建定长数组
  3. 填充定长数组
  4. 返回定长数组
function findTickets(int val) public view returns(Ticket[] memory) {
    uint256 resultCount;

    for (uint i = 0; i < tickets.length; i++) {
        if (tickets[i].val == val) {
            resultCount++;  // step 1 - determine the result count
        }
    }

    Ticket[] memory result = new Ticket[](resultCount);  // step 2 - create the fixed-length array
    uint256 j;

    for (uint i = 0; i < tickets.length; i++) {
        if (tickets[i].val == val) {
            result[j] = tickets[i];  // step 3 - fill the array
            j++;
        }
    }

    return result; // step 4 - return
}

这篇关于SOLIDITY:返回没有推送的经过筛选的结构数组。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆