我怎样才能 return 一个结构体数组?

How can I return an array of struct in solidity?

我正在为执行 投标 的以太坊智能合约设计解决方案。用例包括保留名称,例如。 "myName" 并分配给一个地址。然后,人们可以竞标该名称(在本例中为 myName)。可以有多个名称多次这样的出价

struct Bid {
  address bidOwner;
  uint bidAmount;
  bytes32 nameEntity;
}

mapping(bytes32 => Bid[]) highestBidder;

因此,正如您在上面看到的那样,Bid 结构保存了一个投标人的数据,类似地,映射 highestBidder 中的键(例如 myName)指向此类投标人的数组。

现在,我在尝试 return highestBidder[myName].

时遇到问题

显然,solidity 不支持 returning 结构数组(动态数据)。我要么需要重新设计我的解决方案,要么找到一些解决方法来使其工作。

如果大家对这个问题有任何疑虑,请告诉我,我会尽力说清楚。

我被困在这里任何帮助将不胜感激。

如您所述,Solidity 尚不支持此功能。权力机构正计划对其进行更改,以便您可以,但目前,您必须检索元素的数量,然后将分解的结构检索为元组。

function getBidCount(bytes32 name) public constant returns (uint) {
    return highestBidder[name].length;
}

function getBid(bytes32 name, uint index) public constant returns (address, uint, bytes32) {
    Bid storage bid = highestBidder[name][index];

    return (bid.bidOwner, bid.bidAmount, bid.nameEntity);
}

编辑以解决评论中关于 storagememory 在这种情况下的问题

局部存储变量是指向状态变量的指针(总是在storage中)。来自 Solidity docs:

The type of the local variable x is uint[] storage, but since storage is not dynamically allocated, it has to be assigned from a state variable before it can be used. So no space in storage will be allocated for x, but instead it functions only as an alias for a pre-existing variable in storage.

这是指使用的变量为 uint[] x 的示例。 Bid bid 也适用于我的代码。换句话说,没有创建新的存储。

成本方面:

getBid("foo", 0) 使用 Bid memory bid:

getBid("foo", 0) 使用 Bid storage bid:

在这种情况下,storage更便宜。

关于 "returning an array of structs"...只是一个小的解决方法,以便 return 从 medium

中提取的结构数组
pragma solidity ^0.4.13;

contract Project
{
    struct Person {
        address addr;
        uint funds;
    }

    Person[] people;

    function getPeople(uint[] indexes)
    public
    returns (address[], uint[]) {
        address[] memory addrs = new address[](indexes.length);
        uint[]    memory funds = new uint[](indexes.length);

        for (uint i = 0; i < indexes.length; i++) {
            Person storage person = people[indexes[i]];
            addrs[i] = person.addr;
            funds[i] = person.funds;
        }

        return (addrs, funds);
    }
}

uint[] 索引参数应包含您要访问的索引。

最佳

Return solidity 中的结构数组?
在下面的函数 getBid returns 出价结构数组中。

contract BidHistory {
  struct Bid {
    address bidOwner;
    uint bidAmount;
    bytes32 nameEntity;
  }
  mapping (uint => Bid) public bids;
  uint public bidCount;

  constructor() public {
    bidCount = 0;
    storeBid("address0",0,0);
    storeBid("address1",1,1);
  }
  function storeBid(address memory _bidOwner, uint memory _bidAmount, bytes32 memory _nameEntity) public  {
    bids[tripcount] = Bid(_bidOwner, _bidAmount,_nameEntity);
    bidCount++;
  }
  //return Array of structure
  function getBid() public view returns (Bid[] memory){
      Bid[] memory lBids = new Bid[](tripcount);
      for (uint i = 0; i < bidCount; i++) {
          Bid storage lBid = bids[i];
          lBids[i] = lBid;
      }
      return lBids;
  }
}