Is there a way of creating an immutable array?

Hey guys, just wondering if there is a way of creating an immutable array? Got an error saying

TypeError: Immutable variables cannot have a non-value type.

when creating this object:

uint256[] immutable arr;
2 Likes

It’s currently not supported. I’m not sure if immutables make sense with reference types anyway.

Immutables are values that get embedded into your bytecode at construction time. Value types always take exactly 32 bytes so it’s a a matter of finding the right location and copying the bytes there. Then using them just causes the value to be copied back on the stack.

With reference types the compiler would have to copy the value to memory or storage to let you use it like normal variables of reference types (e.g. pass it into a function or assign it). This defeats the purpose of storing it in the bytecode.

And dynamic types like uint256[] would be especially problematic because they do not have a constant size. Inserting them into the bytecode could shift hard-coded offsets. It might also potentially make your code non-deployable if the value is so large that you go over the size limit.

We’ll likely support constant arrays at some point (there’s already a feature request for structs: Allow initializing constant structs · Issue #4037 · ethereum/solidity · GitHub) but probably not immutables.

The idea I have in mind is a dynamic array of uint256 integers that are unknown until they are assigned values. But once assigned, this array should not be changed. Is there a way of achieving this?

1 Like

What you said makes perfect technical sense. I was also pondering on if the business need is legit. In a scenario where the order of values matters, the values are wished to be locked in some sense. They may be retrieved as a whole and may be deleted as whole. And they could not be known beforehand.

I think this is very close to an immutable array.

I think the concept here may not be the same as that for a integer or string. A workaround can be not providing a function to modify the array is provided, then the array cannot be modified hence immutable.

There is be something to it, especially with people trying to do these things in assembly to save gas. Looks like we might end up adding such a feature after all: Immutable dynamic arrays · Issue #12587 · ethereum/solidity · GitHub

2 Likes

Thanks for considering it. A workaround is not a feature and a feature is better than a workaround. This is coming at the perfect time given EIP-4341 just got merged recently and an immutable array is the ideal data structure to hold a phrase used in this proposal.

Why not have a setter function? (except the gas cost ofcs.)

function setArr(uint256[] memory _arr) external {
    require(arr.length == 0, "Already set");
    for (uint256 i; i < _arr.length; i++) {
        arr[i] = _arr[i];
    }
}

Something like this…