4

Is it possible to have a struct that is or has fields that are constant or immutable?

// struct with constant or immutable fields:
struct MyStruct {
  uint constant number;
  int immutable integer;
}

// struct that instantiates to a constant or immutable variable:
struct MyStruct {
  uint number;
  int integer;
}

MyStruct constant constantMyStruct = MyStruct(1, -1);
MyStruct immutable immutableMyStruct;

// In constructor initialise immutableMyStruct as follows:
immutableMyStruct = MyStruct(1, -1);

If I had to guess constant fields are not possible, since you can't initialise fields to a default in the struct declaration, however I don't see an issue with immutable fields, nor with an immutable or constant instantiation of a struct.

1 Answer 1

4

To understand this, we'll need to look at how constant and immutable work.

Constant

When you declare a variable as constant, the compiler will replace all the instances of the variable with the constant value while compiling. This means, there won't be storage will be allocated for the constant variable. But only values and strings can be created as constants. So Structs, Arrays and Mappings can't be declared as constants according to solidity specs.

Immutable

This is similar, but all the instances of the variables are replaced with the actual value from the constructor during the contract creation time. And also only 32 bytes are reserved for this. This means you cannot create immutable Strings, Arrays, Mappings or structs.

For example, let's deploy the following contract.

contract Something  {
    
    uint public a = 1;
    uint constant public b = 3;
    uint immutable imm;
    
    constructor(uint _imm) {
        imm = _imm;
    }

}

If you look at the state changes made during the creation of this contract, you can see only storage slot 1 changed from 0x0 to 0x1. (see image)

Etherscan Link

Screenshot from etherscan

This should explain why it won't be possible to do what you have mentioned in the question.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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