[Ethereum] How do i loop through an array of structs? “TypeError: Integer constant expected.” Solidity

arrayssoliditystruct

What i want my code to do

Everytime the function is called the exampleValue of all users should be increased by 5

What the code actually does

When i compile it in Remix i get this error message:

TypeError: Integer constant expected. User[i].value = User[i] + 5; ^

Code

pragma solidity 0.6.0;

contract LoopingThroughArray {
    
    struct User {
        uint256 exampleValue;
        address id;
        
    }
    
    User[] public users;
    
    receive() external payable {
        for (uint i=0; i<=users.length; i++) {
            User[i].exampleValue = User[i] + 5;  // thats the line where i get the error
        }  
    }
    
    
} 

What i already tried

  • replacing the users.length with a constant uint both in- and outside of the function
  • using a normal function instead of the receive function

Best Answer

You have reference the mapping name at the index you want, which is a struct and the struct member for the math operations.

pragma solidity 0.6.0;

contract LoopingThroughArray {
    
    struct User {
        uint256 exampleValue;
        address id;
        
    }
    
    User[] public users;
    
    receive() external payable {
        for (uint i=0; i<=users.length; i++) {
            users[i].exampleValue = users[i].exampleValue + 5;
        }  
    }    
} 

CAUTION

I realize this is a contrived example for learning but it is worth mentioning for others who find this example. This approach won't scale. So, either there is a hard limit on users.length or the contract will fail when users.length is too large. This is because the total cost is the cost of one iteration times the number of users in the array. So.

transaction cost = iteration cost * numbers of users

Since there is a soft limit to the gas users would be willing to pay and a hard limit on the gas used by a single transaction in a block, it's not a scalable pattern.

Hope it helps.