我怎样才能返回一个结构数组?

时间:2018-02-20 04:34:39

标签: algorithm data-structures ethereum solidity smartcontracts

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

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

mapping(bytes32 => Bid[]) highestBidder;

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

现在,当我尝试返回类似highBidder [myName] 的内容时,我遇到了问题。

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

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

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

3 个答案:

答案 0 :(得分:4)

正如您所提到的,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);
}

修改以解决有关storage vs memory的评论中的问题

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

  

局部变量x的类型是uint []存储,但由于存储不是动态分配的,因此必须先从状态变量中分配它才能使用它。因此,不会为x分配存储空间,而是仅用作存储中预先存在的变量的别名。

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

就成本而言:

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

enter image description here

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

enter image description here

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

答案 1 :(得分:1)

返回实体数组吗?
在下面的函数 getBid 中返回出价结构数组。

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;
  }
}

答案 2 :(得分:0)

关于“返回结构数组” ...只是一个小解决方法,以便返回从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 []索引参数应包含您要访问的索引。

最佳