1

Trying to add a struct object to a mapping, however the compiler gives error that expected identifier. Here is my code snippet

contract Structs {

    struct User {
        string name;
        uint256 score;
        uint256 balance;
    }

    mapping(address => User) userList;
    User user1 = new User({name : "Jimmy", score : 1 , balance : 100});
    userList[msg.sender] = user1;
}

It gives the error at the following line of code

 userList[msg.sender] = user1;

How do we add new struct object to a mapping?

Thanks

2 Answers 2

1

Nevermind, the code should have been inside a function or so. Here is the updated one, which works fine

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.11;

contract Structs {

    struct User {
        string name;
        uint256 score;
        uint256 balance;
    }

    mapping(address => User) userList;   

    function createUser() external {    
        User memory user1 = User({name : "Liquidus", score : 1 , balance : 100});
        userList[msg.sender] = user1;
    }    
}
1

You need to define a function in which you can add the item to the struct. It is not possible to do so outside of a function.

For your example you could do the following:

contract Structs {

    struct User {
        string name;
        uint256 score;
        uint256 balance;
    }

    mapping(address => User) userList;
    
    function addUser() public {
        User memory user1 = User({name: "Jimmy", score: 1, balance: 100});
        userList[msg.sender] = user1;
    }
}

The addUser function can be called from the constructor if you need this to happen on contract deployment.

In general you should not use new with struct items (this is reserved for contract creation and arrays).

You can find more information in the Solidity docs: https://docs.soliditylang.org/en/v0.8.11/types.html#structs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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