Data Types
Solidity has several built-in data types, including:
Boolean:
boolInteger:
intanduintwith various bit sizes (int8,uint8,int256, etc.)Address:
address, which represents a 20-byte Ethereum addressAddress payable: Defines the
ownervariable as an address that can receive ether. Themsg.senderaddress is cast to this type in the constructor.Fixed-point numbers:
fixedandufixedwith various bit sizes (fixed8x1,ufixed32x18, etc.)Bytes:
bytesandbytewith various sizes (bytes1,byte32, etc.)String:
stringArray:
arraywith a fixed or dynamic size (uint[10],string[], etc.)Struct:
struct, which is a custom data type that groups several variables togetherMapping:
mapping, which is a dynamic array-like data structure that maps keys to values
Data Types Example
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0;
// Enum data type enum Color { Red, Green, Blue }
contract Example { // State variables uint public number; bool public isTrue; string public message; address public owner; address payable public payee; bytes32 public data; fixed256x18 public fixedNumber; Color public color;
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Enum data type
enum Color { Red, Green, Blue }
contract Example {
// State variables
uint public number;
bool public isTrue;
string public message;
address public owner;
address payable public payee;
bytes32 public data;
fixed256x18 public fixedNumber;
Color public color;
// Struct data type
struct Person {
string name;
uint age;
uint[] favoriteNumbers;
}
// Array data type
uint[] public numbers;
// Mapping data type
mapping(address => uint) public balances;
// Constructor
constructor(uint _number, string memory _message, address _owner) {
number = _number;
message = _message;
owner = _owner;
color = Color.Red;
}
// Function that uses a struct
function addPerson(string memory _name, uint _age, uint[] memory _favoriteNumbers) public {
Person memory newPerson = Person({name: _name, age: _age, favoriteNumbers: _favoriteNumbers});
}
// Function that uses an array and a mapping
function addNumber(uint _number) public {
numbers.push(_number);
balances[msg.sender] += _number;
}
}
Data Types Example 2
Last updated