Day 2 - Building a GUI Temperature Converter in Rust
GUI programming with Rust as we build a Temperature Converter using the egui library. From setup to conversion logic, this post guides you through creating an interactive desktop application step by step.
Introduction
Welcome to Day 2 of our Rust project journey! Today, we're stepping into the world of GUI applications with Rust. We'll create a Temperature Converter that allows users to convert between Celsius and Fahrenheit. We'll use egui
, a simple yet powerful GUI library for Rust, for this project.
Prerequisites
- Rust installed on your system (
rustup
andcargo
) - Basic knowledge of Rust syntax
Project Setup
Step 1: Create a New Rust Project
Open your terminal and run:
Step 2: Add Dependencies
Edit your Cargo.toml
to include:
Step 3: Project Structure
Your project should now look like this:
rust_temperature_converter/
├── Cargo.lock
├── Cargo.toml
└── src/
└── main.rs
Step 4: Implementing the Converter
Now, replace the content in src/main.rs
with:
Explanation of the Code
-
Main Function: Here we set up the application window using
eframe::NativeOptions
. Therun_native
function starts the application with ourTempConverter
struct as the app state. -
TempConverter Struct: This holds our state, namely
celsius
andfahrenheit
temperatures. We implementDefault
for easy initialization. -
App Implementation: We implement the
eframe::App
trait forTempConverter
. Theupdate
method is where the UI logic resides:- We use
CentralPanel
for our main window content. text_edit_singleline
allows users to input or see temperature values.- Buttons trigger temperature conversions using the formulas:
- Celsius to Fahrenheit:
(°C × 9/5) + 32
- Fahrenheit to Celsius:
(°F - 32) × 5/9
- Celsius to Fahrenheit:
- We use
Running the Project
- Save your
main.rs
file. - From the terminal, in the project directory, run:
You should now see a window appear with input fields for Celsius and Fahrenheit temperatures and buttons to convert between them.
Conclusion
Congratulations! You've now created a functional GUI in Rust. This project not only teaches GUI interaction but also basic temperature unit conversion. As you continue with Rust, consider exploring different GUI libraries or adding more features like Kelvin conversion or saving conversion history.
Keep coding, and see you tomorrow for Day 3! 🚀