Solidity is an object-oriented, high-level, and compiled programming language for writing smart contracts, in addition to building and deploying Dapps on completely different blockchains.
Solidity, like every other programming language, has its personal knowledge varieties and knowledge constructions, however with a unique syntax and utility.
This tutorial will go over among the most frequently used knowledge varieties and knowledge constructions in Solidity programming languages.
Nature of Solidity Information Varieties
Solidity is a statically typed, strongly typed language in nature that performs sort checking earlier than the supply code is executed.
As a statically typed language, Solidity requires the programmer to declare the information sort of every variable forward of compiling the code (compile-time).
Whereas Solidity as a strongly typed language means the information sort of a variable can’t be modified or transformed to a different knowledge sort inside the program.
Solidity Information Varieties
Solidity, like different programming languages, divides its knowledge varieties into two classes: worth varieties and reference varieties.
Worth Varieties in Solidity
A worth sort variable is one which shops knowledge immediately within the stack reminiscence allotted to itself.
These varieties are handed by worth, which implies they’re copied anytime they’re assigned to a brand new variable or provided as an argument to a perform and any adjustments made to the brand new copies don’t have an effect on the unique knowledge.
1.) Integers
The integer knowledge sort in Solidity is used to retailer integer values. An integer sort is additional grouped into int and uint used to declare signed and unsigned sort of integers respectively.
i. The int/signed integer
The int
key phrase is used to declare signed integers. The signed integer is a knowledge sort that may maintain each optimistic and unfavourable integer values in good contracts.
pragma solidity ^ 0.8.13;
contract Signed_Integer_Example{
int yr = 2022;
int temperature = -89;
}
ii. The uint/unsigned integer
The uint
key phrase is used to declare unsigned integers. The unsigned integer is a knowledge sort that may solely maintain optimistic integer values in good contracts.
pragma solidity ^ 0.8.13;
contract Unsigned_Integer_Example{
uint yr = 2022;
uint temperature = -89;
}
If you attempt to assign a unfavourable worth to an unsigned knowledge sort, you’ll obtain the next TypeError
message:
TypeError: Sort int_const -89 is not implicitly convertible to anticipated sort uint256. Can not implicitly convert signed literal to an unsigned sort.
2.) Bytes
Bytes in Solidity are fixed-size byte arrays that comprise a sequence of bytes. The size of the byte array is outlined on the entrance of the bytes as in bytes1
to bytes32
.
The quantity is equal to the variety of characters the byte array variable can comprise.
pragma solidity ^ 0.8.13;
contract Bytes_Array_Example{
bytes1 one_character = "a";
bytes2 two_characters = "ab";
bytes3 three_characters = "abc";
bytes4 four_characters = "abcd";
bytes5 five_characters = "abcde";
bytes32 thrity_two_characters = "abcdefghijklmnopqrstuvwxyz123456";
}
If you try to assign various characters that exceed the fastened measurement of bytes, as proven beneath:
pragma solidity ^ 0.8.13;
contract Bytes_Array_Example{
bytes1 one_character = "ab";
bytes1 two_characters = "abc";
}
You’ll obtain the next TypeError
message:
TypeError: Sort literal_string "abc" is just not implicitly convertible to anticipated sort bytes1. Literal is bigger than the kind.
3.) Booleans
Boolean in Solidity is denoted by the bool
key phrase and like each different programming language, boolean in Solidity accepts simply two values: true
and false
:
pragma solidity ^ 0.8.13;
contract Boolean_Example{
bool isEthereumMerge = true;
bool currentUserCanMintToken = false;
bool isRaining = "true";
bool isAdmin = "false";
}
If you attempt to assign a non-boolean worth to a boolean variable, you’ll obtain the next TypeError
message:
TypeError: Sort literal_string "true" is not implicitly convertible to the anticipated sort bool.
4.) Tackle
The deal with is a particular knowledge sort in Solidity, able to receiving and sending Ether to and from it. The deal with knowledge sort is designed to retailer an Ethereum deal with, which often begins with the 0x
worth.
Addresses are 20 bytes in measurement and comprise 42 characters.
0x0000000000000000000000000000000000000000
Addresses are additionally non-case-sensitive hexadecimal digits generated from the Keccak-256 hash of the public key.
If you attempt to assign a string to an deal with knowledge sort, as proven beneath:
pragma solidity ^ 0.8.13;
contract Address_Example{
deal with user_address = 0x0000000000000000000000000000000000000000;
deal with user_home_address = "Avenue 2, downtown street";
}
You will get the next TypeError
message:
TypeError: Sort literal_string "Avenue 2, downtown street" is not implicitly convertible to anticipated sort deal with.
If you attempt to assign a non-hexadecimal quantity to an deal with knowledge sort, as proven beneath with an octal quantity:
pragma solidity ^ 0.8.13;
contract Address_Example{
deal with user_address = 0x0000000000000000000000000000000000000000;
deal with phone_address = 080123456789;
}
You will get the next ParserError
message:
ParserError: Octal numbers not allowed.
Tackle worth varieties are additional divided into two:
perform | deal with |
deal with payable |
---|---|---|
Examine deal with stability | ✅ | ✅ |
Ship Ether | ❌ | ✅ |
Obtain Ether | ❌ | ✅ |
Professional Tip: If you need your good contract to obtain and ship Ether, use the deal with payable
worth sort. When you do not need your good contract to obtain or switch Ether, use the plain deal with
worth sort.
5.) Enums
Enum knowledge varieties, often known as enumerations, allow builders to create user-defined knowledge varieties. The user-defined knowledge are names assigned to an integral fixed worth ranging from zero.
pragma solidity ^ 0.8.13;
contract Enum_Example{
enum Standing {
Sending,
Success,
Failed
}
Standing standing;
perform sendSomething () public {
standing = Standing.Sending;
}
}
From the code snippet above, we created a Standing
enum that holds the standing of motion once we ship one thing. We will then use the enum to replace the standing of the motion to any of the predefined statuses within the Standing
enum.
Reference Varieties in Solidity (Information Construction)
A reference sort variable is one which shops the situation (reminiscence deal with) of their knowledge on the Heap reminiscence and so they do not share their knowledge immediately.
Modifications made to the reference knowledge will at all times have an effect on the unique knowledge.
Examples of reference varieties in Solidity embody strings, structs, arrays, and mapping.
1.) String
The string
sort is a sequence of characters. Solidity helps each string literals utilizing single-quotes ' '
and double-quotes " "
.
pragma solidity ^ 0.8.13;
contract String_Example{
string identify = "John Doe";
}
2.) Structs
The struct
knowledge sort is a reference knowledge sort that can be utilized to create a construction of different knowledge varieties. A struct can comprise each worth sort and reference sort together with different structs however not a struct of itself.
A struct will be created in Solidity utilizing the syntax beneath:
struct <Struct_Name> {
<data_type> <variable_name>;
}
The data_type
is usually a string
, int
, uint
, bool
, or any solidity knowledge sort. Structs will be declared exterior of a wise contract and imported into one other contract.
A use case of a struct will be seen beneath:
pragma solidity ^ 0.8.13;
contract Struct_Example{
struct UserProfile {
string fullName;
bool isOnboarded;
uint age;
}
UserProfile _newUserProfile = UserProfile("Ayodele Samuel Adebayo", true, 19);
perform getUserProfile() public view returns (string reminiscence, bool , uint ){
return (_newUserProfile.fullName, _newUserProfile.isOnboarded, _newUserProfile.age);
}
}
From the code above; we created a struct for the consumer profile that expects a fullName
, the isOnboarded
standing, and the consumer age
. We then use this construction to create a brand new consumer with a perform that returns the data of the created profile.
Takeaway: Utilizing structs in Solidity makes our code extra organized, maintainable, reusable, and readable.
3.) Arrays
An array is a group of variables with the identical knowledge sort. They’re saved in a steady reminiscence location with every array merchandise having a singular index.
Array in Solidity will be fastened or dynamic in measurement and every array merchandise will be searched by its distinctive index.
i. Dynamic Array
A dynamic array will be created in Solidity utilizing the syntax beneath:
pragma solidity ^ 0.8.13;
contract Dynamic_Array_Syntax{
<datatype[]> <variable_name> = <[array_items]>
}
Under is an instance of a string
dynamic array of names and a uint
dynamic array of numbers:
pragma solidity ^ 0.8.13;
contract Dynamic_Array_Example{
string[] arrayOfNames = ["Faith", "Becky", "Steve"];
uint[] arrayOfNumbers = [0, 1, 2, 3, 4, 5];
}
ii. Mounted-Dimension Array
A set-size array will be created utilizing the syntax beneath:
pragma solidity ^ 0.8.13;
contract Fixed_Size_Array_Syntax{
<datatype[size]> <variable_name> = <[array_items]>
}
Under is an instance of a 2 fixed-sized string
array of names and 1 fixed-sized uint
dynamic array of numbers:
pragma solidity ^ 0.8.13;
contract Fixed_Size_Array_Example{
string[2] arrayOfNames = ["Faith", "Becky"];
uint[1] arrayOfNumbers = [0];
}
If you attempt to exceed the fixed-size restrict:
pragma solidity ^ 0.8.13;
contract Fixed_Size_Array_Example{
string[2] arrayOfNames = ["Faith", "Becky", "Steve"];
uint[1] arrayOfNumbers = [0, 1, 2];
}
You will get the next TypeError
messages, respectively:
TypeError: Sort string[3] reminiscence is not implicitly convertible to anticipated sort string[2] storage ref.
TypeError: Sort uint8[3] reminiscence is not implicitly convertible to anticipated sort uint256[1] storage ref.
4.) Mapping
Mapping in Solidity is a key-value pair knowledge construction that features equally to a dictionary in Python and hashtables or objects in JavaScript.
Mapping will be created in Solidity with the next syntax:
pragma solidity ^ 0.8.13;
contract Mapping_Syntax{
mapping (key => worth) variable_name;
}
The place the key
will be any knowledge sort aside from reference sort and the worth
will be each worth sort and reference sort.
Under is an instance of mapping customers’ pockets addresses to their balances:
pragma solidity ^ 0.8.13;
contract Mapping_Example{
mapping (deal with => uint) users_balances;
}
From the above knowledge construction implementation, we will retrieve the crypto stability of customers from the blockchain in uint
sort utilizing their pockets deal with
.
Wrapping Up
Information varieties and knowledge constructions are the muse of any programming language and the constructing blocks for growing superior Dapps with Solidity.
On this tutorial, we have gone via essentially the most generally used knowledge varieties and knowledge constructions in Solidity programming language.
What’s Subsequent?
Now that you have discovered in regards to the knowledge varieties and knowledge constructions in Solidity:
This text is part of the Hashnode Web3 blog, the place a workforce of curated writers are bringing out new assets that will help you uncover the universe of web3. Examine us out for extra on NFTs, DAOs, blockchains, and the decentralized future.