Build a Counter App in Rust egui — Buttons and State (Ep 3)
Video: Build a Counter App in Rust egui — Buttons and State (Ep 3) by Taught by Celeste AI - AI Coding Coach
Watch full page →Build a Counter App in Rust egui — Buttons and State (Ep 3)
In this tutorial, you'll learn how to create an interactive counter app using Rust's egui library. We'll cover how to add buttons with ui.button(), detect clicks using .clicked(), arrange UI elements horizontally with ui.horizontal(), and manage mutable state within your app struct. Additionally, we'll demonstrate splitting your code into multiple files with mod and use for better organization.
Code
use eframe::{egui, epi};
struct CounterApp {
count: i32, // mutable state to track the counter value
}
impl Default for CounterApp {
fn default() -> Self {
Self { count: 0 }
}
}
impl epi::App for CounterApp {
fn name(&self) -> &str {
"Counter App"
}
fn update(&mut self, ctx: &egui::CtxRef, _frame: &epi::Frame) {
egui::CentralPanel::default().show(ctx, |ui| {
ui.label(format!("Count: {}", self.count));
// Arrange buttons horizontally
ui.horizontal(|ui| {
if ui.button("+").clicked() {
self.count += 1; // increment count on + button click
}
if ui.button("-").clicked() {
self.count -= 1; // decrement count on - button click
}
});
});
}
}
fn main() {
let app = CounterApp::default();
let native_options = eframe::NativeOptions::default();
eframe::run_native(Box::new(app), native_options);
}
Key Points
- Use
ui.button()to create clickable buttons in egui. - Detect button presses with the
.clicked()method to update state. ui.horizontal()arranges UI elements side-by-side for better layout.- Store mutable state like the counter value inside your app struct for interactivity.
- Organize code by splitting into modules with
modandusefor clarity and reuse.