Overview
TheSimpleStorage contract is a foundational smart contract that demonstrates core Solidity concepts. It manages a favorite number and maintains a list of people with their associated favorite numbers.
Key Features:
- Store and retrieve a favorite number
- Manage a dynamic list of people with their favorite numbers
- Quick name-to-number lookup using mappings
- Demonstrates structs, arrays, and mappings in action
Contract Structure
State Variables
myFavoriteNumber- Stores a single unsigned integer (initialized to 3)listOfPeople- Dynamic array of Person structsnameToNumber- Maps person names to their favorite numbers for efficient lookup
Data Types
Person Struct
Person struct defines a custom data type that bundles together a person’s name and their favorite number.
Core Functions
store()
_favoriteNumber- The new favorite number to store
public - Can be called by anyone
This is a state-changing function that costs gas to execute since it modifies blockchain storage.
retrieve()
myFavoriteNumber
Visibility: public view - Read-only function that doesn’t cost gas when called externally
addPerson()
_name- The person’s name (stored in memory during function execution)_favoriteNumber- The person’s favorite number
- Creates a new
Personstruct - Adds it to the
listOfPeoplearray - Creates a mapping entry for name-based lookup
The
memory keyword indicates that _name is temporarily stored in memory during function execution, not permanently in contract storage.Full Contract Code
Usage Examples
- Store a Number
- Retrieve a Number
- Add People
Concepts Demonstrated
Data Types
uint256for numbersstringfor text- Custom
structtypes
Storage Structures
- Dynamic arrays (
Person[]) - Mappings for key-value pairs
- State variables
Functions
- State-changing functions
viewfunctions for reading- Public visibility
Memory Keywords
memoryfor temporary data- Understanding storage locations
Key Takeaways
SimpleStorage teaches fundamental Solidity concepts:
- How to declare and use state variables
- Working with structs, arrays, and mappings
- The difference between view and state-changing functions
- Memory vs storage data locations
- Public visibility and automatic getters