Search code examples
structblockchainethereumsoliditysmartcontracts

How to save structs in array in Solidity?


I wrote a very simple smart contract which does the following:

  • Declares a struct named Player which has 2 fields: name and goals
  • Defines a function which takes as inputs names and goals to create a new instance of the structure
  • Stores the new player into an array of players

Here is the code:

pragma solidity ^0.8.0;
    
contract MyContract {
    
    // Declare struct
    struct Player {
        string name;
        uint goals;
    }
    
    // Declare array
    Player[] player;
    
    function addPlayer(string calldata _name, uint _goals) external pure{
    
       Player memory player = Player({name:_name, goals:_goals}); // This declaration shadows an existing declaration.
    
       players.push(player); // Member "push" not found or not visible after argument-dependent lookup in struct MyContract.Player memory.
    
    }
    
}

My goal is to use the addPlayer() function to add players to the players array However the VisualStudio Editor returns an error since it gets confused by the declaration of the Player variable which appears to be twice.

Could you please provide a smart and elegant way to achieve my goal please?


Solution

  • // SPDX-License-Identifier: MIT
    pragma solidity ^0.8.0;
        
    contract MyContract {
        
        // Declare struct
        struct Player {
            string name;
            uint goals;
        }
        
        // Declare array
        Player[] players;
        
        function addPlayer(string calldata _name, uint _goals) external {
        
           Player memory player = Player(_name,_goals); // This declaration shadows an existing declaration.
        
           players.push(player); // Member "push" not found or not visible after argument-dependent lookup in struct MyContract.Player memory.
        
        }
        
    }