Writing Functions To Modify Structs Directly In Solidity Mappings

Dean Schmid
3 min readAug 3, 2019

--

I’m not sure what to call this, but I want to share a solidity pattern that I have used extensively.

Cryptozombies teaches us how to initialize structs directly into arrays

zombieArray.push(Zombie(id, name, owner));

That isn’t the exact code, but I am sure you know what I mean.

Zombie is the struct and it has three properties (id, name, owner)

When you have a struct

struct ExampleStruct {string property; }

You can initialise it by doing something like this.

ExampleStruct nameOfStruct = ExampleStruct("property");

To make this more dynamic you would probably include it in a function and pass it properties as arguments. That would, in turn, require you to specify if the struct it being stored in storage (On the blockchain forever), or in memory (only existing for the duration of the function execution).

Example:

function passArgumentsToStruct(string memory property) public {

ExampleStruct memory s = ExampleStruct(property);
}

Cool, cool, cool. The property can now come from another function, contract or user, but it’s still a little restrictive.

Cryptozombies teaches us to initialise structs in an array because it makes a lot of sense. Your structs are stored sequentially and they are accessible. It makes sense to wrap our data type in another data type - but arrays pffftttt. Let’s use our function to put our struct in a mapping.

struct ExampleStruct {
uint luckyNumber;
}


mapping (uint => Player) public StructMapping;


function putStructInMapping(uint index, uint _luckyNumber) public {
StructMapping[index].luckyNumber = _luckyNumber;}

Mappings are strange.

Every possible position — key — in a mapping already exists, and it’s just waiting for you to come along and overwrite it with something useful. That’s why you can [index] a position in the StructMapping that should be empty, accesses its undefined properties with dot notation then set them to your function parameters.

Mappings can be seen as hash tables which are virtually initialized such that every possible key exists and is mapped to a value whose byte-representation is all zeros — solidity docs

Look at this.

I will ask the mapping getter function what is at key 4. This is a brand new contract instance.

Instead of returning undefined or a big red error, it returned an empty struct instance at key 4

At key 5 million

The exact same output.

--

--

Dean Schmid
Dean Schmid

Written by Dean Schmid

Full-Stack Developer, Web Designer. I’m a Lover of the Internet and all the Opportunity it Brings.

No responses yet