Control Structures and Data Structures in Solidity
Control Structures
Solidity follows the same syntax of control structures as Java script or C.
So there is: if, else, while, do, for, break, continue, with the usual semantics known from C or JavaScript.
Syntax of if-else block :
if(condition)
//do something
else
//do something
Syntax of while loop :
while(condition){
//do something
}
Syntax of for loop :
for(uint i = 0; i <= n; i++)
{
//do something
}
Syntax of do-while loop :
do{
//do something
} while(condition);
Structs
A struct is a special data type that allows the programmer to group a list of variables.
Syntax :
struct MyProfile{
string firstname;
string lastname;
uint16 age;
bool isMarried;
}
Arrays
When you want a collection of something, you can use an array. There are two types of arrays in Solidity : fixed arrays and dynamic arrays.
Array with a fixed length of 2 elements, containing integers :uint[2] fixedArray;
Another fixed Array, can contain 5 strings :
string[5] stringArray;
A dynamic Array — has no fixed size, can keep growing:uint[] dynamicArray;
An array of structs :StructName[] variablename;
Working With Structs and Arrays
Consider the Struct we previously created
struct MyProfile{
string firstname;
string lastname;
uint16 age;
bool isMarried;
}
MyProfile[] public people;
Now let’s see how to create new Person’s objects and add them to our people array.
Create a New Person:Person James = Person(“James”,”Ryan”,35,true);
Add that person to the Array:people.push(James);
We can also combine these together and do them in one line of code to keep things clean:people.push(Person(“James”,”Ryan”,35,true));
Mappings
Mappings allow the programmer to create key-value pairs for storing(as a list) and looking up data.
Syntax :
mapping(key_type => key_value) mappingName;
Two commonly used data types [ key_type ] for mapping keys are address and uint.
It is important to note that not every data type can be used as a key. For instance, structs and other mappings cannot be used as keys.
Unlike with keys, Solidity does not limit the data type for values [ key_values ]. It can be anything, including structs and other mappings.
A mapping to hold the bank account balance in uint for the given address : mapping(address => uint) balance;
A mapping to store usernames based on userId :mapping (uint => string) userIdToName;
Yay!!! 🎉 That wraps up the basics of control structures and data structures.
Please check me out on LinkedIn as well, I would love to hear from you!