Solidity struct as parameter

Total
0
Shares
Solidity struct as parameter

In Solidity it wasn’t possible to pass struct as parameter but with the introduction of experimental library ABIEncoderV2, it could be done.

Solution

pragma solidity ^0.5.3;
pragma experimental ABIEncoderV2;

contract simpleContract {
  struct Person {
    string name;
    uint age
  } 
  
  function setPerson (Person p) public view{
    Person user = P;
  }

}

Code Explanation

In this code I have used experimental ABIEncoderV2 to pass a struct as a parameter because solidity does not provide any feature to pass a struct as a parameter to a function on a smart contract.

In the code, we defined a struct Person with members – name and age. name is a string type and age is uint. We also defined a function setPerson where we are passing this struct as parameter.

Reason

The use of structs in your function parameters can significantly reduce the clutter of so many variable of different data types into different function. You might not feel this problem when you are writing small contract. But for complex structs, it’s a trouble.

It also reduces the complexity of your contracts while enabling them to be much more pleasant to interact with whenever someone uses it.

Conclusion

Solidity is ever evolving technology and you can find newer and newer solutions for different problems including this. So don’t keep a close mind and keep looking for new solutions.

Sign Up for Our Newsletters

Get only the best articles delivered to your mail

You May Also Like
solidity enum example

Solidity Enum Example

Table of Contents Hide IntroductionCodeThings to know about enumRelated Posts: Introduction The word enum in solidity stands for Enumerable as it does in most of the other languages. Enum is…
View Post