0

I am trying to push multiple items to the array of structs in the contract. Couldn't find a clear answer if it is possible to pass an array of struct as a parameter.

Apparently I can't but I get a different kind of an error from the compiler. It thinks I am passing a mapping: Only libraries are allowed to use the mapping type in public or external functions.

Here's the code

mapping (address => Review[]) reviewsMap;
mapping (address => uint24) reviewCounts;

function addMultipleReviews(Review[] memory array) public {
    address author = msg.sender;
    for (uint i=0; i < array.length; i++) {
      reviewsMap[author].push(array[i]);
    } 
    reviewCounts[author] = reviewCounts[author] + array.length;
  }

Is this not allowed? If so what would be an alternative to add multiple Reviews?

  • You are not allowed to pass structs (or an array of structs in your case). What is Review? Instead of passing an array of this struct, pass several arrays, one for each one of the fields in this structure. Then construct a Review instance before pushing it to reviewsMap[author]. – goodvibration Dec 9 '19 at 14:59
  • Review is the struct defined in the contract. I already have an addReview function to add a single Review, which takes each single field as parameters, bundles them in a Review struct and pushes into the array. addReview(string memory a, uint32 b) public Is what you are suggesting passing arrays of fields as such? addMultipleReviews(string memory a[], uint32 b[]) public – kuzdogan Dec 9 '19 at 15:03
  • Yes. And at the beginning of the function, assert(a.length == b.length);. – goodvibration Dec 9 '19 at 15:04
  • Thanks. You can write it as an answer if you'd like. – kuzdogan Dec 9 '19 at 15:06
0

You are not allowed to pass structs (or an array of structs in your case).

Instead of passing an array of Review elements, pass several arrays - one for each field in this struct.

Then construct a Review instance before pushing it to reviewsMap[author].

I recommend asserting that the lengths of the arrays are identical.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.