0

This my code ..if someone can help ..thanks in advance

pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2 ;
contract Users {
    struct Drug {  // Vehicle = Drug
         string name;
        uint Qt;
        uint Qs;
        uint Qr;
    }
 

    event DrugAdded(
        string name,
      uint Qt,
      uint Qs,
      uint Qr
    );
    Drug[] public drugs;
 uint counter=0;
    function addDrug(string memory _name, uint _Qt, uint _Qs, uint _Qr) public {
       drugs.push(
            Drug(_name, _Qt,_Qs,_Qr)
        );
        emit DrugAdded(_name, _Qt,_Qs,_Qr);
        counter++;
    }

    function getdrugs(string memory _name) public view returns (Drug[] memory) {
        for(uint i=0;i<counter;i++){
            if (keccak256(abi.encodePacked((drugs[i].name))) == keccak256(abi.encodePacked((_name)))){
                return drugs[i];
            }
        }
       
    }
}

i get error in last line: TypeError: Return argument type struct Users.Drug storage ref is not implicitly convertible to expected type (type of first return variable) struct Users.Drug memory[] memory. return drugs[i]; ^------^

Imen
  • 23
  • 3

1 Answers1

0

Because of how arrays are stored in memory, Solidity is not able to resize memory arrays. So when you're returning a dynamic-length array with an unknown length, you need to find out and declare its length first (see _getCount() in the example below) - and then fill each of its items.

You can find another example of a very similar thing in this answer.

function getdrugs(string memory _name) public view returns (Drug[] memory) {
  Drug[] memory drugsToReturn = new Drug[](_getCount(_name));
  uint256 index = 0;

  for(uint i=0;i<counter;i++) {
      if (keccak256(abi.encodePacked((drugs[i].name))) == keccak256(abi.encodePacked((_name)))){
        drugsToReturn[index] = drugs[i];
        index++;
      }
  }
    
  return drugsToReturn;
}

function _getCount(string memory _name) private view returns (uint256) {
  uint256 count = 0;

  for(uint i=0;i<counter;i++) {
      if (keccak256(abi.encodePacked((drugs[i].name))) == keccak256(abi.encodePacked((_name)))){
          count++;
      }
  }

  return count;
}
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100