返回一个Structs数组



我想返回一个结构体数组,因为我想输出我所有的数据。

//SPDX-License-Identifier:MIT
pragma solidity ^0.8.0;
contract MyContract
{
mapping(uint256 => People) dataList;
uint256[] countArr;
struct People{
string name;
uint256 favNum;
}

在这个函数中,我设置了struct对象的数据,然后将其包含在我的映射中。

function setPerson(string memory _name,uint256 _id, uint256 _favNum) public {
dataList[_id]= People(_name,_favNum);
countArr.push(_id);
}

这个函数获取我指定的struct对象的数据。

function getPerson(uint _id) public view returns(string memory,uint256){
return (dataList[_id].name, dataList[_id].favNum);
}

现在这里是函数,我认为这给我带来了麻烦,因为在这个函数中,我想返回的不是单个人对象的数据,而是我所有的数据,每当我在REMIX IDE控制台上运行这个函数时,它都会向我显示错误:调用我的合同。getAllData error:虚拟机错误:恢复。回复事务已恢复到初始状态。注意:如果你发送值并且你发送的值应该小于你当前的余额,那么被调用的函数应该是支付的。

function getAllData()public view returns(People[] memory){
uint256 count = countArr.length;
uint256 i = 0;
People[] memory outputL= new People[](count);
while(count >= 0){
(string memory nam,uint256 num) = getPerson(count-1);
People memory temp = People(nam,num);
outputL[i]=temp;
count--;
i++;
}
return outputL;
}                
}

谁能帮助和解释什么是错的,我怎么能让它运行?

这个版本的getAllData函数如您所期望的那样工作:

function getAllData() public view returns (People[] memory) {
uint256 count = countArr.length;
People[] memory outputL = new People[](count);
while(count > 0) {
count--;
(string memory nam, uint256 num) = getPerson(countArr[count]);
People memory temp = People(nam, num);
outputL[count] = temp;
}
return outputL;
} 

如有任何问题,请提出来。