33

Is it possible to store structs in a Mapping or any dynamic memory structure in my Solidity SmartContract?

3 Answers 3

40

You can store structs as the values of your mapping, not as the key. Here is some more info: http://solidity.readthedocs.org/en/latest/types.html#structs

struct Funder {
  address addr;
  uint amount;
}

struct Campaign {
  address beneficiary;
  uint fundingGoal;
  uint numFunders;
  uint amount;
  mapping (uint => Funder) funders;
}

uint numCampaigns;
mapping (uint => Campaign) campaigns;
0
11

Yes, you can.

For example, in the solidity code below. There is a struct User that has a mapping of friends, from address to another struct Friend.

Then there's a mapping of users, from address to User [note that User is a struct].

struct Friend {
    string name;
    string email;
    string phoneNumber;
}

struct User {
    string name;
    string email;
    uint256 balance;
    mapping (address => Friend) friends;
}

mapping (address => User) public users;

So, say a user A has friends B, C, and D. The User can be imagined to look like this:

{
    name: 'A',
    email: [email],
    balance: [balance],
    friends: {
        [address_of_friend_B]: {
            name: 'B',
            email: [email],
            phoneNumber: [phoneNumber],
        },
        [address_of_friend_C]: {
            name: 'C',
            email: [email],
            phoneNumber: [phoneNumber],
        },
        [address_of_friend_D]: {
            name: 'D',
            email: [email],
            phoneNumber: [phoneNumber],
        },
    }
}

And if there are many such User structs, say A, J, Z, ..., the mapping users holds them all:

{
    name: 'A',
    ...
    friends: {...},

    name: 'J',
    ...
    friends: {...},

    name: 'Z',
    ...
    friends: {...},
}

So yes, you can store structs in a mapping.

0

yes, you can use struct in map like this:

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;

contract MyFriends{
    struct Friends{
        string name;
        string[] girlfriends;
        bool isSingle;
    }

    mapping(uint=>Friends) FriendsInfo;
}

wrong codes:

mapping(Friends=>uint) FriendsInfo;
2
  • Then how to set value and fetch value?
    – Hacek
    Apr 19, 2023 at 19:12
  • you need to make solidity functions to get and post data in map
    – aakash4dev
    Apr 25, 2023 at 11:52

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.