Solidity the language of smart contracts is somewhat similar to java or other Object Oriented Programming(OOP) Languages. Alot data types in solidity are similar to data types of Java or C++, but it does have some very interesting and different data types for specifically writing smart contracts.
1. int and uint:-
int and uint is signed(stores both positive and negative integer) and unsigned(stores only positive integer) integers ranging from 8bits to 256 bits.
In C++ int can store upto 32bits(10^9) and long long upto 64bits(10^18).
In solidity int or int256 can store a value upto 10^77.
int256 a = -2; // signed integer, int == int256
uint256 b = 4; // unsigned integer, uint == uint256
2. bool:-
boolean in solidity is same as other languages except in Solidity bool cannot be converted to integers, as they can in other programming languages.
in C++ we can do this
if(1)
{
return "Hello World";
}
But the same code will give us error TypeError: Type int_const 1 is not implicitly convertible to expected type bool.
3. address and address payable:-
address is a special data type in solidity to store 20byte size ethereum address.
Here msg.sender
is the person or other contract which called this contract.
address owner;
function ownerSetter() public
{
owner = msg.sender;
}
After invoking the ownerSetter()
function the value of owner
became 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4
.
You can use .balance
to get the balance of the address.
function checkBalance() public view returns(uint)
{
return owner.balance;
}
The only difference between address
and address payable
is that we can actually transfer ether to the address.
address payable
is same as address
but with additional features like:
- send();
- transfer();
- call();
4. fixed-sized byte arrays:-
fixed-sized byte arrays range from bytes1
,bytes2
upto bytes32
. byte array store the data in the form of hexadecimal digits. bytes uses less gas as compare to string.
bytes3 public b3 = "abc";
bytes2 public b2 = "ab";
bytes are immutable which means we cannot change the state of the object after it is created.
This will throw us error in remix IDE
bytes3 public b3 = "abc";
b3[1] = 'a';
Also you can not store integers directly in bytes, for e.g.
bytes1 public b1 = 0x61; // Works
bytes1 public b2 = 1; // Doesn't Work
bytes1 public b3 = "1"; // Works
Here b2
will throw error. 0x61
is hexadecimal value of 'a'
5. enum:-
Enum is a user-defined type in Solidity. Think of enum as state manager, for e.g.
If we want to change the state of computer at a given time we can use enum for that.
Enum makes a program easy to read and maintainable.
enum states{Active, Sleep, Terminated}
states public Computer_State = states.Active; // Assigning default value to Active
function changeStateToSleep() public
{
Computer_State = states.Sleep; // Changing state to sleep
}
Thank you for reading all the way through. Please let me know if the article (or the code) can be improved in any way in the comments down below.