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

up vote 22 down vote accepted

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;

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.

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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