Solidity is an object-oriented, high-level, and compiled programming language for writing smart contracts, in addition to building and deploying Dapps on totally different blockchains.
Solidity, like every other programming language, has its personal knowledge varieties and knowledge constructions, however with a special syntax and software.
This tutorial will go over among the most frequently used knowledge varieties and knowledge constructions in Solidity programming languages.
Nature of Solidity Knowledge Varieties
Solidity is a statically typed, strongly typed language in nature that performs kind checking earlier than the supply code is executed.
As a statically typed language, Solidity requires the programmer to declare the information kind of every variable forward of compiling the code (compile-time).
Whereas Solidity as a strongly typed language means the information kind of a variable can’t be modified or transformed to a different knowledge kind throughout the program.
Solidity Knowledge Varieties
Solidity, like different programming languages, divides its knowledge varieties into two classes: worth varieties and reference varieties.
Worth Varieties in Solidity
A price kind 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 operate and any adjustments made to the brand new copies don’t have an effect on the unique knowledge.
1.) Integers
The integer knowledge kind in Solidity is used to retailer integer values. An integer kind is additional grouped into int and uint used to declare signed and unsigned kind of integers respectively.
i. The int/signed integer
The int
key phrase is used to declare signed integers. The signed integer is an information kind that may maintain each constructive and unfavourable integer values in sensible 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 an information kind that may solely maintain constructive integer values in sensible contracts.
pragma solidity ^ 0.8.13;
contract Unsigned_Integer_Example{
uint yr = 2022;
uint temperature = -89;
}
While you attempt to assign a unfavourable worth to an unsigned knowledge kind, you’ll obtain the next TypeError
message:
TypeError: Kind int_const -89 is not implicitly convertible to anticipated kind uint256. Can not implicitly convert signed literal to an unsigned kind.
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";
}
While you try and assign quite a few characters that exceed the mounted dimension 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: Kind literal_string "abc" shouldn't be implicitly convertible to anticipated kind bytes1. Literal is bigger than the sort.
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";
}
While you attempt to assign a non-boolean worth to a boolean variable, you’ll obtain the next TypeError
message:
TypeError: Kind literal_string "true" is not implicitly convertible to the anticipated kind bool.
4.) Tackle
The deal with is a particular knowledge kind in Solidity, able to receiving and sending Ether to and from it. The deal with knowledge kind is designed to retailer an Ethereum deal with, which normally begins with the 0x
worth.
Addresses are 20 bytes in dimension and comprise 42 characters.
0x0000000000000000000000000000000000000000
Addresses are additionally non-case-sensitive hexadecimal digits generated from the Keccak-256 hash of the public key.
While you attempt to assign a string to an deal with knowledge kind, as proven beneath:
pragma solidity ^ 0.8.13;
contract Address_Example{
deal with user_address = 0x0000000000000000000000000000000000000000;
deal with user_home_address = "Avenue 2, downtown highway";
}
You will get the next TypeError
message:
TypeError: Kind literal_string "Avenue 2, downtown highway" is not implicitly convertible to anticipated kind deal with.
While you attempt to assign a non-hexadecimal quantity to an deal with knowledge kind, 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:
operate | deal with |
deal with payable |
---|---|---|
Verify deal with stability | ✅ | ✅ |
Ship Ether | ❌ | ✅ |
Obtain Ether | ❌ | ✅ |
Professional Tip: While you need your sensible contract to obtain and ship Ether, use the deal with payable
worth kind. When you do not need your sensible contract to obtain or switch Ether, use the plain deal with
worth kind.
5.) Enums
Enum knowledge varieties, also called 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;
operate sendSomething () public {
standing = Standing.Sending;
}
}
From the code snippet above, we created a Standing
enum that holds the standing of motion after we ship one thing. We are able to 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 (Knowledge Construction)
A reference kind variable is one which shops the placement (reminiscence deal with) of their knowledge on the Heap reminiscence and so they do not share their knowledge immediately.
Adjustments 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
kind 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 title = "John Doe";
}
2.) Structs
The struct
knowledge kind is a reference knowledge kind that can be utilized to create a construction of different knowledge varieties. A struct can comprise each worth kind and reference kind together with different structs however not a struct of itself.
A struct may be created in Solidity utilizing the syntax beneath:
struct <Struct_Name> {
<data_type> <variable_name>;
}
The data_type
could be a string
, int
, uint
, bool
, or any solidity knowledge kind. Structs may be declared outdoors of a wise contract and imported into one other contract.
A use case of a struct may 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);
operate 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 person profile that expects a fullName
, the isOnboarded
standing, and the person age
. We then use this construction to create a brand new person with a operate 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 kind. They’re saved in a steady reminiscence location with every array merchandise having a singular index.
Array in Solidity may be mounted or dynamic in dimension and every array merchandise may be searched by its distinctive index.
i. Dynamic Array
A dynamic array may 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 hard and fast-size array may 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];
}
While 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: Kind string[3] reminiscence is not implicitly convertible to anticipated kind string[2] storage ref.
TypeError: Kind uint8[3] reminiscence is not implicitly convertible to anticipated kind uint256[1] storage ref.
4.) Mapping
Mapping in Solidity is a key-value pair knowledge construction that capabilities equally to a dictionary in Python and hashtables or objects in JavaScript.
Mapping may 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
may be any knowledge kind aside from reference kind and the worth
may be each worth kind and reference kind.
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
kind utilizing their pockets deal with
.
Wrapping Up
Knowledge varieties and knowledge constructions are the inspiration of any programming language and the constructing blocks for growing superior Dapps with Solidity.
On this tutorial, we have gone by essentially the most generally used knowledge varieties and knowledge constructions in Solidity programming language.
What’s Subsequent?
Now that you’ve got realized concerning the knowledge varieties and knowledge constructions in Solidity:
This text is part of the Hashnode Web3 blog, the place a staff of curated writers are bringing out new sources that will help you uncover the universe of web3. Verify us out for extra on NFTs, DAOs, blockchains, and the decentralized future.