Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot push to array in a struct #1491

Open
LucasSte opened this issue Aug 16, 2023 · 4 comments
Open

Cannot push to array in a struct #1491

LucasSte opened this issue Aug 16, 2023 · 4 comments
Labels
bug Something isn't working

Comments

@LucasSte
Copy link
Contributor

This contract:

contract Foo {
	struct My {
		bytes bb;
	}
	function bar() public pure returns (uint32) {
		My s;
		s.bb.push(2);
		return s.bb.length;
	}
}

causes this error:

thread 'main' panicked at 'not an array', src/sema/types.rs:1415:18
@LucasSte LucasSte added the bug Something isn't working label Aug 17, 2023
@Shiva953
Copy link

bb declared with bytes is a dynamic byte array and it doesn't have a push method like arrays in some other programming languages. To do that, you gotta manage the length of the array manually and use memory allocation functions.

  1. Declare s as a memory variable. This would allow you to modify data(array in this case) inside of the bar function as it is declared as pure. It aligns with the function's read-only nature and preventing errors related to modifying storage in a read-only context.
  2. Initialize the bytes array s.bb using new bytes(0).
pragma solidity ^0.8.0;

contract Foo {
    struct My {
        bytes bb;
    }

    function bar() public pure returns (uint256) {
        My memory s; //declare s as a memory variable
        s.bb = new bytes(0); // Initialize the bytes array
        s.bb.push(0x02);

        return s.bb.length;
    }
}

@LucasSte
Copy link
Contributor Author

Thanks @Shiva953, you are right.
solc does not allow us to push to a bytes array that is not in memory. The bug, however, still exists. The compiler must not panic because we are trying to build incorrect code. It should raise an error.

@Shiva953
Copy link

yeah sire, that's a solidity compiler limitation and I honestly don't have the slightest of the clues about anything related to compilers

@seanyoung
Copy link
Contributor

Solang does support push/pop on memory arrays, even if solc does not. However, it should not panic.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

4 participants
@seanyoung @LucasSte @Shiva953 and others