Data Types

Solidity has several built-in data types, including:

  1. Boolean: bool

  2. Integer: int and uint with various bit sizes (int8, uint8, int256, etc.)

  3. Address: address, which represents a 20-byte Ethereum address

  4. Address payable: Defines the owner variable as an address that can receive ether. The msg.sender address is cast to this type in the constructor.

  5. Fixed-point numbers: fixed and ufixed with various bit sizes (fixed8x1, ufixed32x18, etc.)

  6. Bytes: bytes and byte with various sizes (bytes1, byte32, etc.)

  7. String: string

  8. Array: array with a fixed or dynamic size (uint[10], string[], etc.)

  9. Struct: struct, which is a custom data type that groups several variables together

  10. Mapping: 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