Skip to main content

Command Palette

Search for a command to run...

Using Solidity Types

A Quick Overview & Example

Updated
2 min read
Using Solidity Types

1. Boolean

The boolean type represents a binary value: true or false. It's commonly used for conditional statements and flags.

bool isActive = true;
bool isAuthorized = false;

if (isActive) {
    // Execute code if isActive is true
}

2. Integer

Integers are used to represent whole numbers. Solidity provides several integer types with different ranges.

uint8 smallNumber = 42;  // Unsigned integer (0 to 255)
int256 largeNumber = -1000;  // Signed integer (-2^255 to 2^255-1)

3. Address

The address type is used to store Ethereum addresses. It can represent both externally owned addresses and contract addresses.

address owner = 0xAbCdEf0123456789012345678901234567890abcd;

4. String

Strings are used to store text data. They are enclosed in double quotes.

string greeting = "Hello, Solidity!";

Advanced Types

Solidity also supports more complex types that allow you to define custom structures.

1. Array

Arrays allow you to store a collection of elements of the same type.

uint[] numbers;  // Dynamic array
uint[5] fixedSizeArray;  // Fixed-size array with 5 elements

numbers.push(10);  // Add element to dynamic array
fixedSizeArray[2] = 42;  // Assign value to element at index 2

2. Mapping

Mappings are key-value stores where you can associate values with unique keys.

mapping(address => uint) balances;

balances[msg.sender] = 1000;  // Assign balance to the sender's address
uint myBalance = balances[msg.sender];  // Get sender's balance

3. Struct

Structs allow you to define custom data structures with multiple fields.

struct Person {
    string name;
    uint age;
}

Person alice = Person("Alice", 30);

Putting It All Together

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract TypesDemo {
    bool public isActive = true;
    uint public totalSupply = 1000;
    address public owner = 0xAbCdEf0123456789012345678901234567890abcd;
    string public greeting = "Hello, Solidity!";

    uint[] public numbers;
    mapping(address => uint) public balances;
    struct Person {
        string name;
        uint age;
    }
    Person public alice;

    constructor() {
        numbers.push(10);
        balances[msg.sender] = 1000;
        alice = Person("Alice", 30);
    }
}

Conclusion

That wraps up our quick overview and exploration of types in Solidity! Choose the appropriate type for your data to ensure your contracts run efficiently and accurately.

Happy coding, and stay tuned for more coding tutorials. 😁

More from this blog

Damian Robinson | Online

20 posts

The blog and business site of Damian Robinson. You will find tutorials about programming and cybersecurity, and articles pertaining to various interests or pursuits of the author.