Skip to content
This is my space, where experience meets the will to start over. This is my space, where experience meets the will to start over.

The first step is knowing where you want to go.

  • Home
  • Coding Hub
    • Software & Project
      • Small Biz Ops – S.B.O.
        • SmallBizOps – Day 10/90
      • CRM/ERP
      • MyTracker
      • My Budget
    • Form Zero to “WoW”
      • JavaScript from Zero (Completed)
        • 2. Remove and Edit List Items
        • 3. Separate HTML and JavaScript, Use addEventListener and Conditional Logic
        • 4. Add Dynamic CSS Classes
        • 5. Save & Restore Your List with localStorage
        • 6 – Turn Your App into a Full To-Do List
      • Python from Zero (Completed)
        • 2. Lists & Loops
        • 3. Conditional Menus
        • 4. Edit & Remove Tasks (with closing: Python vs PHP and Large Data)
        • 5 – Save to File: Make Your Tasks Survive Restarts
        • 6 — Pythin from zero – Final Project Polishing: Numbering, Formatting, and Preparing for CSV
      • Rust – From Zero to “WoW” (Completed)
        • 1 – Setup and Project Structure in Rust
        • 2 – User input: validation and error handling
        • 3 – Rust from Zero to “WoW – BMI Calculation and Conditional Logic
        • 4 –Rust – Clear, Formatted Output
        • 5 – Rust – Final Thoughts: Precision as a Form of Respect
      • Go from Zero to “WoW” (Completed)
        • 1 – Why Go Is Perfect for a Personal Expense Tracker
        • 2 – Logging Expenses and Console Input
        • 3 – Go from Zero to “WoW” – Smart Filtering & Display Logic
        • 4 – Go – Saving Data to Local Files
        • 5 – Go – Final Project – Expense Tracker in Go
      • C++ from Zero to “WoW” (Completed)
        • 1 – Why C++ for file organization?
        • 2 – C++ – File Type Detection and Classification
        • 3 – C++ – Creating & Managing Subfolders
        • 4 – C++ – Safe File Movement and User Feedback
        • 5 – C++ – Order as Mental Clarity
      • Ubuntu – From Zero to “WoW” (Completed)
        • 2 – Ubuntu – The Desktop Environment and Essential Commands
        • 3 – Ubuntu – Managing Files, Folders, and Permissions
        • 4 – Ubuntu – Installing and Updating Software with APT and Snap
        • 5 – Ubuntu – Customizing the Desktop Environment
        • 6 – Ubuntu – Network and Device Configuration
        • 7 – Ubuntu – User Management & System Security — “The Cathedral of Permissions”
        • 8 – Ubuntu – The Talking Machine: Terminal & Bash Scripting
        • 9 – Ubuntu – Ubuntu as a Server or Development Environment
        • 10 – Ubuntu – Backup, Maintenance & Troubleshooting
    • Git Hub Repository
      • Small Biz Ops – S.B.O.
      • Mini ERP – PHP & MySQL
      • CleverCRM (Java, Spring Boot)
      • FraudWatch (Python, FastAPI + scikit-learn)
      • OnboardIQ – Smart Onboarding Portal (Flask + SQLite Demo)
    • ArchPilot
      • 1-Users & Roles, End-to-End (Architecture, Database, and Cross-Framework Code)
      • 2 – Client Registry (CRM) Across Frameworks
      • 3 – Project & Budget Tracker (ERP)
      • 4 – Approval Workflow Engine Multi-step routing, status tracking, escalation paths
      • 5 – Audit Trail & Versioning
    • Small Biz Ops – S.B.O.
  • Vivere in USA
  • P4Y
  • Testi poetici
    • 1 – Sospeso
    • 2 – Il bicchiere di vetro quieto
    • 3 – Quando l’amore inciampa
    • 4 – Ma chi siete davvero?
    • 5 – Above the Thread of Day
    • 6 – The Truth That Doesn’t Exist
    • 7 – All of You, I Miss
    • 8 – The Captain and the Ocean
    • 9 – Between Light and Mist
    • 10 – Il peso delle scelte
  • Contact
  • Admin
This is my space, where experience meets the will to start over.
This is my space, where experience meets the will to start over.

The first step is knowing where you want to go.

Coding – Step 11.2 – Rust from Zero to “WoW” –User input: validation and error handling

Posted on 27 Settembre 202527 Settembre 2025 By Francesco

In the previous chapters, we introduced the philosophy of Rust and set up our development environment. Now it’s time to interact with the user — collecting data that will power our BMI calculator.

But here’s the truth: we can’t trust user input. It might be letters instead of numbers, strange values like 0 or negatives, or even an empty line. Rust forces us to treat every input as potentially wrong, and this is where its philosophy of rigor shines.


We’ve created our Rust project and confirmed that everything works. The next step is to let the user enter data. In our case, we want to collect weight and height in order to calculate BMI.

But here’s the catch: when we ask for input, we can’t trust it.

  • The user might type letters instead of numbers.
  • They might enter strange values, like 0 or negative numbers.
  • They might just press Enter without writing anything.

In Rust, whenever we deal with uncertain data, we must handle errors in a clear and safe way. This chapter is about learning the first steps with input, parsing, and validation.


Reading input from the keyboard

Rust uses the std::io library to read from the keyboard. Let’s see the simplest example:

use std::io;

fn main() {
    let mut input = String::new(); // create an empty string
    println!("Enter your weight in kg:");

    io::stdin() // take the "standard input"
        .read_line(&mut input) // read a line and save it into 'input'
        .expect("Failed to read input");

    println!("You entered: {}", input);
}

What happens here?

  1. We create a mutable variable (mut input) that will store what the user types.
  2. io::stdin().read_line(&mut input) → reads until the Enter key.
  3. expect("Failed...") stops the program with a message if something goes wrong.

Converting the input into a number

The value we read is always a string. But to calculate BMI we need numbers. We use .trim().parse():

let weight: f32 = input.trim().parse().expect("You must enter a number!");
  • .trim() → removes spaces and line breaks.
  • .parse::<f32>() → tries to convert to a decimal number (f32 = floating point).
  • .expect() → if it fails, the program stops with the error.

Not ideal yet, because stopping the program isn’t very user-friendly. But it shows us what happens if you type letters instead of numbers.


Handling errors gracefully

In Rust, we can use match to manage both success and error cases:

let weight: f32 = match input.trim().parse() {
    Ok(num) => num, // success: return the number
    Err(_) => {
        println!("Error: please enter a valid number.");
        return; // exit the program
    }
};

This way the program doesn’t crash but shows a clear message.


Creating a reusable function

To avoid writing the same code twice (for weight and height), we can create a function:

fn read_number(prompt: &str) -> f32 {
    loop {
        let mut input = String::new();
        println!("{}", prompt);

        std::io::stdin()
            .read_line(&mut input)
            .expect("Failed to read input");

        match input.trim().parse::<f32>() {
            Ok(num) if num > 0.0 => return num, // valid number
            Ok(_) => println!("The value must be greater than zero."),
            Err(_) => println!("Invalid input, please try again."),
        }
    }
}

And in main:

fn main() {
    let weight = read_number("Enter your weight in kg:");
    let height = read_number("Enter your height in meters:");
    println!("Weight: {}, Height: {}", weight, height);
}

What we learn here:

  • We use an infinite loop (loop { ... }) that only ends when the user enters valid data.
  • match handles three cases:
    1. Valid number (> 0).
    2. Valid number but not realistic (0 or negative).
    3. Conversion error (letters instead of numbers).

End-of-chapter reflection

Many languages treat input as “probably fine” and deal with errors later. Rust is different:

  • Every input is treated as potentially wrong.
  • The compiler forces us to think about errors, and that makes the program safer.
  • Even a simple BMI calculator becomes an exercise in care and respect for the user.

The result? A small program that never crashes and patiently guides the user until they do the right thing. That’s our first real “wow” moment in Rust.

Post Views: 345

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Rust Coding beginnersbmi calculatorerror handlingProgrammingrustUser Input

Navigazione articoli

Previous post
Next post

Francesco

My name is Francesco Boschi, originally from Italy and currently based in the United States. For over twenty years, I’ve worked as a manager and consultant across diverse sectors — from education and cultural institutions to the food industry — developing skills in operational management, strategic consulting, and complex problem-solving. In recent years, I’ve combined this experience with a strong passion for software development, creating custom tools designed to simplify workflows and meet real business needs.

Relocating to the U.S. marks the beginning of a new chapter: a personal and professional decision driven by the desire to be close to my son and to embrace new challenges in a different environment. Today, my goal is to turn my experience into meaningful solutions, blending strategic vision with technical expertise to help people and organizations work more effectively.

I enjoy moving between different worlds, adapting tools and approaches to people and contexts. I bring leadership, flexibility, attention to detail, analytical thinking, and a strong problem-solving mindset — along with a deep curiosity to learn and grow. Above all, I believe in sharing: I’m always eager to offer my experience to support the growth of others.

Related Posts

Python

Coding – Step 10.2 – Python from Zero – Lists & Loops

Posted on 3 Agosto 20253 Agosto 2025

Store, Repeat, Automate 🧭 Introduction In the previous lesson, you learned how to use variables to store single values.But in real life, we deal with lists of things: shopping items, tasks, names, scores.And to process multiple items efficiently, we use lists and loops. 📦 1. Lists in Python ✅ Basic…

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Read More
Coding

Coding – Step 8 – The Most Popular Programming Languages: Different Tools, One Common Logic

Posted on 14 Luglio 202526 Luglio 2025

When people talk about coding, the conversation often starts with: “What’s the best language?” Is it JavaScript or Python? PHP or Java?In reality, the better question is: What kind of project do I want to build, and which tool fits that purpose best? The 5 Most Used Programming Languages in…

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Read More
Coding

Coding – Step 13.5 – C++ – Order as Mental Clarity

Posted on 18 Ottobre 202518 Ottobre 2025

C++ file organizer that categorizes files by extension, moves them into folders, and provides clear feedback.

Condividi:

  • Condividi su Facebook (Si apre in una nuova finestra) Facebook
  • Condividi su X (Si apre in una nuova finestra) X
Read More

Iscriviti alla nostra Newsletter

🤞 Let's keep in touch

We do not send spam! Read our Privacy policy for more information.

Controlla la tua casella di posta o la cartella spam per confermare la tua iscrizione

Cerca nel sito

©2026 This is my space, where experience meets the will to start over. | WordPress Theme by SuperbThemes