[英]Returning an Array of Structs Solidity
I want to return an array of structs because i want to output all my data.我想返回一个结构数组,因为我想输出我的所有数据。
//SPDX-License-Identifier:MIT
pragma solidity ^0.8.0;
contract MyContract
{
mapping(uint256 => People) dataList;
uint256[] countArr;
struct People{
string name;
uint256 favNum;
}
In this function, i set the data of my struct object and then include it in my mapping.在这个函数中,我设置了我的结构对象的数据,然后将它包含在我的映射中。
function setPerson(string memory _name,uint256 _id, uint256 _favNum) public {
dataList[_id]= People(_name,_favNum);
countArr.push(_id);
}
This function here gets me the data of my specified struct object.这个函数在这里获取我指定的结构对象的数据。
function getPerson(uint _id) public view returns(string memory,uint256){
return (dataList[_id].name, dataList[_id].favNum);
}
Now here is the function i think that is causing me trouble because in this function i want to return not the data of a single People object but all of my data and whenever i run this function on my REMIX IDE console it shows me the error: call to MyContract.getAllData errored: VM error: revert.现在这是我认为给我带来麻烦的函数,因为在这个函数中我想返回的不是单个 People 对象的数据,而是我的所有数据,每当我在我的 REMIX IDE 控制台上运行这个函数时,它都会向我显示错误:调用 MyContract.getAllData 出错:VM 错误:还原。 revert The transaction has been reverted to the initial state. revert事务已恢复到初始状态。 Note: The called function should be payable if you send value and the value you send should be less than your current balance.注意:如果您发送值并且您发送的值应该小于您当前的余额,则调用的函数应该是应付的。
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;
}
}
Can anyone help and explain what is wrong and how can i get it running?任何人都可以帮助解释什么是错的,我怎样才能让它运行?
This version of the getAllData
function works as you expect:此版本的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;
}
Feel free to ask if you have any questions about the changes.如果您对更改有任何疑问,请随时询问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.