0

I have a struct in solidity defined as follows:

struct Batch{
    address payable owner;
    address payable[] precedentsOwners;
    uint[] precedentsBatches;
}

I want to create a function that allows me to append a list of owners to this struct, but i get a lot of errors... Is there any way to do this?

Thanks a lot.

1 Answers1

1

You can use the push() array method to add items into a storage array.

Mind that your array is address payable type, so if you're passing a regular address (see the argument of appendToOwners()), you need to cast it as payable first.

pragma solidity ^0.8;

contract MyContract {
    struct Batch{
        address payable owner;
        address payable[] precedentsOwners;
        uint[] precedentsBatches;
    }
    
    Batch public myBatch;
    
    function appendToOwners(address _newOwner) external {
        myBatch.precedentsOwners.push(payable(_newOwner));
    }
}
Petr Hejda
  • 40,554
  • 8
  • 72
  • 100
  • Thanks a lot Petr! I'll let you know if it worked! – tommasoLovergine96 May 31 '21 at 21:12
  • @Petr Hejda, do you have an idea how to add struct into array of struct and return this from the function? Compiler tells me I can push only on ```storage``` and return from function only ```memory``` or ```calldata``` – Joe Dow Aug 22 '22 at 13:39
  • @JoeDow Solidity currently doesn't allow resizing in-memory arrays because of how the memory is structured. So you'll need to initialize an empty in-memory array with predefined length and then fill its values. You can find an example in [this answer](https://stackoverflow.com/a/68010807/1693192). – Petr Hejda Aug 22 '22 at 13:49