[Ethereum] Returning Struct Array in solidity

contract-debuggingcontract-developmentsolidity

contract TripHistory {
       struct Trip {
           string lat;
           string lon;
       }
        mapping(string => Trip[]) trips;

        function getTrip(string _trip_id) public view returns (Trip[]) {
            return trips[_trip_id];
        }
        function storeTrip(string _trip_id, string _lat, string _lon) public  {
           trips[_trip_id].push(Trip(_lat, _lon));
        }

}

This is my contract code. Here I'm trying to store the coordinates of a particular trip. While storing the information contract executing fine. But When I retrieve the data, It should give the array of coordinates. But it is throwing an error.

reason: 'insufficient data for uint256 type'

What I'm missing here. Is there any other way to achieve what I'm trying here. Kindly help me out.

P.S: I'm new to solidity.

Best Answer

Return an array of struct from a function

contract TripHistory {
  struct Trip {
    string lat;
    string lon;
  }
  mapping (string => Trip) public trips;
  uint public tripcount;

  constructor() public {
    tripcount = 0;
    storeTrip("let0","long0");
    storeTrip("let1","long1");
  }
  function storeTrip(string memory _lat, string memory _lon) public  {
    trips[tripcount] = Trip(_lat, _lon);
    tripcount++;
  }
  //return Array of structure
  function getTrip() public view returns (Trip[] memory){
      Trip[] memory trrips = new Trip[](tripcount);
      for (uint i = 0; i < tripcount; i++) {
          Trip storage trrip = trips[i];
          trrips[i] = trrip;
      }
      return trrips;
  }
}
Related Topic