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

问题描述 投票:3回答:2

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

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

mapping(bytes32 => Bid[]) highestBidder;

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

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

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

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

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

algorithm data-structures ethereum solidity smartcontracts
2个回答
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);
}

编辑以解决有关storagememory的评论中的问题

本地存储变量是指向状态变量的指针(总是在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更便宜。


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 []索引参数应包含您要访问的索引。

最好

© www.soinside.com 2019 - 2024. All rights reserved.