可靠性:以公共方法返回数组

时间:2019-06-05 23:38:51

标签: solidity

我正在尝试创建一个返回数组的公共函数, 这是错误

  

返回参数类型映射(uint256 =>结构ItemList.Item存储   ref)不能隐式转换为预期的类型(第一个类型   返回变量)uint256 []内存。

pragma solidity ^0.5.0;
contract ItemList {
    uint public itemCount = 0;
    mapping(uint256 => Item) public items;

    event ItemCreated (
        uint id,
        string proofdocument
    );

    struct Item {
        uint id;
        string proofdocument;
    }

    constructor() public {
    }

    function createItem(string memory _proofdocument) public {
        itemCount++;
        items[itemCount] = Item(itemCount, _proofdocument);
        emit ItemCreated(itemCount, _proofdocument);
    }

    function getItems() public pure returns(uint256[] memory ) {
        return items; <----------ERROR
    }
}

感谢安德里亚

1 个答案:

答案 0 :(得分:0)

您可以通过web3.js库获取循环中的所有项目

const array = []
for (let i = 0; i < itemCount; itemCount += 1) {
    array.push(contract.getItem(i)) // where getItem do items[I] in solidity
}

或者您可以使用pragma experimental版本:

pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;

contract ItemList {
    uint public itemCount = 0;

    struct Item {
        uint id;
        string proofdocument;
    }
    Item[] items;

    constructor() public {}

    function createItem(string memory _proofdocument) public {
        itemCount++;
        items.push(Item(itemCount, _proofdocument));
    }

    function getItems() external view returns(Item[] memory) {
        return items;
    }
}