Overview
Solidity is a statically-typed language, meaning you must declare the type of each variable. Understanding data types and storage structures is fundamental to writing efficient smart contracts.Basic Data Types
Unsigned Integers
The most common numeric type in Solidity isuint256 (unsigned integer with 256 bits):
SimpleStorage.sol
uint256 can hold values from 0 to 2^256 - 1. The uint keyword is shorthand for uint256.Other Common Types
address- Ethereum addresses (20 bytes)bool- Boolean values (true/false)string- Text databytes- Raw byte dataint256- Signed integers (can be negative)
Structs
Structs allow you to create custom data types by grouping related variables:SimpleStorage.sol
- Explicit Constructor
- Named Parameters
Arrays
Arrays store ordered lists of elements. They can be fixed-size or dynamic.Dynamic Arrays
SimpleStorage.sol
Dynamic arrays can grow in size using the
push() method. The size is not predetermined.Fixed-Size Arrays
Mappings
Mappings are key-value stores, similar to hash tables or dictionaries in other languages:SimpleStorage.sol
How Mappings Work
- Keys can be any built-in type (except mappings, structs, or arrays)
- Values can be any type, including other mappings
- All possible keys exist and map to the default value (0 for numbers)
- You cannot iterate over mappings
Advanced Mapping Syntax
Solidity 0.8.18+ supports clearer mapping declarations:FundMe.sol
Storage Locations
When working with reference types (arrays, structs, mappings, strings), you must specify a data location:Memory
Temporary data that exists only during function execution:Storage
Permanent data stored on the blockchain:Calldata
Read-only temporary data (more gas-efficient than memory for external function parameters):State variables (declared at contract level) are always in storage. Function parameters need explicit data location for reference types.
Practical Example
Here’s the complete SimpleStorage contract demonstrating all concepts:SimpleStorage.sol
Key Takeaways
- Use
uint256for non-negative numbers,int256for signed numbers - Structs group related data into custom types
- Arrays store ordered collections; use dynamic arrays with
push() - Mappings provide O(1) lookups but cannot be iterated
- Specify
memoryfor temporary function parameters,calldatafor read-only parameters - State variables are automatically stored in blockchain storage