Rust egui Text Input — Build a Greeting Form (Ep 4)
Video: Rust egui Text Input — Build a Greeting Form (Ep 4) by Taught by Celeste AI - AI Coding Coach
Watch full page →Rust egui Text Input — Build a Greeting Form
In this tutorial, you will learn how to create a simple interactive greeting form using Rust and the egui GUI library. By adding a text input field, you can capture user input in real time and display a personalized greeting that updates instantly as the user types.
Code
use eframe::egui;
struct GreetingApp {
name: String, // Stores the user input
}
impl Default for GreetingApp {
fn default() -> Self {
Self {
name: String::new(),
}
}
}
impl eframe::App for GreetingApp {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
egui::CentralPanel::default().show(ctx, |ui| {
// Create a single-line text input bound to self.name
ui.label("Enter your name:");
ui.text_edit_singleline(&mut self.name);
// Display a greeting if the input is not empty
if !self.name.is_empty() {
ui.label(format!("Hello, {}!", self.name));
} else {
ui.label("Please type your name above.");
}
});
}
}
fn main() {
let options = eframe::NativeOptions::default();
eframe::run_native(
"Greeting Form",
options,
Box::new(|_cc| Box::new(GreetingApp::default())),
);
}
Key Points
- Use
text_edit_singleline(&mut String)to create a text input field bound to mutable state. - Store user input in a
Stringfield within your app's state struct. - Pass a mutable reference
&mutto bind the input widget directly to your state. - Leverage egui's immediate mode to update the UI live as the user types.
- Use
is_empty()to check for empty input and conditionally display messages.