Ethereum: storing structs in a mapping

It turns out that in addition to storing primitive values such as uints and addresses in Ethereum, you can store more complicated and customized values as well. A struct, short for “structure”, allows you to put several primitives together, assign this group of primitives with a name, and address the group as you would an object.

One reason that you might want to store a struct is separation of concerns. Separation of Concerns is an important concept in programming that encourages combining related data for the purpose of organization.

Let’s take an example from the docs, for instance:

contract CrowdFunding {
    // Defines a new type with two fields.
    struct Funder {
        address addr;
        uint amount;
    }

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

This example is only a subset of code from the full contract, but it’s use of encapsulation shows that a Campaign has items such as numFundersamount, and also number of funders. In fact, these funders are stored as another mapping between an index and a Funder.

If we wanted to keep a mapping of campaigns, that is, a group a campaigns indexed by some uint index, we could define such a mapping like this:

 mapping (uint => Campaign) campaigns;

And just like that, we’ve expressed the relationships between a fairly large set of data in a simple way. To access a campaign, we’d address the mapping as we would with any other, simpler, mapping:

campaigns[campaignID]

Happy programming!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s