Definining a Solidity struct with dynamic field

In Javascript, it’s possible to add fields to an object even after its creation, dynamically:

const user = {
  name: 'James',
  age: 20
};

user.email = 'james@gmail.com';

In Solidity, there aren’t objects, but instead we have structs and fields. So, can we dynamically add fields of Solidity structs AFTER they were defined?

struct User {
  string name;
  uint age;
}

function createUser() external {
  User memory user = User('James', 20);
  user.email = 'james@gmail.com; // Solidity will not like it!
}

Unfortunately, Solidity will not let you do this… Let’s not forget that contrary to Javascript Solidity is a statically-typed language. That means you need to define a type before you can use it. And once your type is defined you can’t change it.

So, no, the above code is not possible. However, what you could do is define all the struct fields in advance, and let one of the fields empty upon creation, or with a value that is supposed to mean undefined:

struct User {
  string name;
  uint age;
  string email;
}
mapping(uint => User) users;

//First create an user with empty email
function createUser() external {
  User memory user = User('James', 20, '');
  users.push(user);
}

//Later you can update the value of the email field
function updateEmail(uint i, string calldata email) external {
  users[i].email = email;
}

On the one hand It’s not as convenient as in Javascript, but on the other hand with Solidity and static typing you get stronger guarantees that you are not making mistakes with your data.

What do you think? Do you have other solutions for dealing with dynamic data in Solidity?

1 Like