Counter Example
The counter example is the “Hello, World!” of GUI programming with Iced. It demonstrates the core concepts of Iced’s architecture in the simplest possible way.What You’ll Learn
- Basic Iced application structure
- State management
- Message handling
- Button widgets
- Text rendering
- Layout with columns
Complete Source Code
Here’s the complete counter example fromexamples/counter/src/main.rs:
Breaking It Down
1. Application Entry Point
iced::run function is the simplest way to start an Iced application. It takes two functions:
update: How to modify state based on messagesview: How to render the current state
2. State Definition
Default derive allows Iced to initialize it automatically.
3. Messages
Clone and typically should be Debug for easier debugging.
4. Update Logic
5. View Logic
column!macro creates a vertical layoutbutton().on_press()creates clickable buttons that emit messagestext()displays the current value.padding()and.align_x()style the layout
Testing
The counter example includes tests using Iced’s testing framework:- Creating a UI simulator
- Simulating user clicks
- Processing messages
- Verifying state changes
- Checking UI content
Running the Example
Key Concepts
The Elm Architecture
Iced follows The Elm Architecture pattern:- Model (State) - The current application state
- Update - A function that transforms state based on messages
- View - A function that renders state into UI
- Predictable state updates
- Easy testing
- Clear separation of concerns
- Time-travel debugging capability
Immutability
While theupdate function takes &mut self, the pattern encourages thinking about state as immutable. Each update creates a new logical state.
Type Safety
Rust’s type system ensures:- Messages are handled exhaustively
- State transitions are valid
- UI and logic stay in sync
Next Steps
Once you understand the counter:- Try adding a reset button
- Add a text input to set the counter value
- Experiment with different layouts (row instead of column)
- Try different widget styles and themes
- Move on to the todos example for a more complex application
Related Examples
- Styling - Learn about themes and custom styles
- Todos - A more complete application
- Events - Handle keyboard and other events
