Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying The Rust Programming Handbook
  • Table Of Contents Toc
The Rust Programming Handbook

The Rust Programming Handbook

By : Francesco Ciulla
5 (1)
close
close
The Rust Programming Handbook

The Rust Programming Handbook

5 (1)
By: Francesco Ciulla

Overview of this book

The Rust Programming Handbook is a deeply engaging and meticulously crafted book designed to immerse programmers into the intricate world of Rust’s core principles and sophisticated features. This book not only enhances your coding skills but also prepares you to tackle complex challenges in software development, optimizing your code for better performance and reliability. You will explore Rust’s powerful concurrency models, rigorous memory safety guarantees, and its versatile trait system. Discover the foundational elements that make Rust a standout language for developing safe and efficient applications. The book will show you how these core principles can seamlessly transition into real-world applications. You will learn how to apply Rust's capabilities to systems programming and web development, extending the reach of its safety and efficiency benefits across different programming domains. Whether it's creating low-level system components or high-performance web services, the book provides practical examples to integrate Rust effectively into a variety of projects. Elevate your coding skills and become a sought-after professional in the tech industry with this essential guide. Rust from Beginner to Professional is your definitive toolkit for mastering advanced Rust programming techniques and writing high-quality code.
Table of Contents (20 chapters)
close
close
18
Other Books You May Enjoy
19
Index

Your first real Rust program: a CLI calculator

While a "Hello, World!" program is an excellent first step, it only touches the surface of what Rust is capable of. Let’s take it a step further by building a simple command-line calculator that can perform basic arithmetic operations based on user input.

This small project will introduce you to key concepts in Rust, including the following:

  • Handling user input using std::io
  • Using functions to organize code efficiently
  • Error handling with match expressions
  • Working with numbers and string parsing using the parse() method

Step 1: Setting up your project

First, create a new Rust project using Cargo:

cargo new cli_calculator
cd cli_calculator

Open src/main.rs in your favorite IDE and let’s start coding!

Step 2: Writing the calculator logic

We will build a simple calculator that does the following:

  • Prompts the user for two numbers
  • Asks for an operation (+, -, *, or /)
  • Performs the calculation and displays the result

Here’s the complete code, followed by a deeper explanation (Don’t worry if you don’t fully understand the code below. This is just to get used to the Rust code. We will get into all the concepts and constructs used in the example below in the upcoming chapters. Take this as a trailer!):

// Import the standard input/output library to handle user input
use std::io;
fn main() {
    // Display a welcome message to introduce the program
    println!("Welcome to the Rust CLI Calculator!");
    
    // Prompt the user to enter the first number
    // We use a helper function `get_number` to handle input validation
    let num1 = get_number("Enter the first number: ");
    
    // Prompt the user to enter the second number
    let num2 = get_number("Enter the second number: ");
    
    // Prompt the user to enter an operation
    println!("Enter an operation (+, -, *, /):");
    // Create a mutable string to store the user's input
    let mut operation = String::new();
    // Read the user's input and store it in `operation`
    io::stdin().read_line(&mut operation).expect("Failed to read input");
    // Trim any whitespace (e.g., newline) from the input
    let operation = operation.trim(); 
    // Perform the calculation based on the chosen operation
    let result = match operation {
        "+" => Some(num1 + num2), // Addition
        "-" => Some(num1 - num2), // Subtraction
        "*" => Some(num1 * num2), // Multiplication
        "/" => {
            // Before dividing, check that the second number is not zero
            if num2 != 0.0 {
                Some(num1 / num2) // Division
            } else {
                println!("Error: Division by zero is not allowed.");
                None // Return None if division by zero is attempted
            }
        }
        _ => {
            // If the user enters an invalid operation, print an error message
            println!("Invalid operation. Please enter +, -, *, or /.");
            None // Return None to indicate an invalid operation
        }
    };
    // If the result is valid (not None), print the result
    if let Some(res) = result {
        println!("Result: {}", res);
    }
}
// This function prompts the user to enter a number and ensures valid input
fn get_number(prompt: &str) -> f64 {
    loop { // Infinite loop until valid input is provided
        println!("{}", prompt); // Display the prompt message
        let mut input = String::new(); // Create a new mutable string for user input
        io::stdin().read_line(&mut input).expect("Failed to read input"); // Read input
        // Try to convert the input string into a floating-point number (f64)
        match input.trim().parse::<f64>() {
            Ok(num) => return num, // If parsing succeeds, return the number
            Err(_) => println!("Invalid number. Please enter a valid numeric value."), // If parsing fails, prompt again
        }
    }
}

Let’s look at a detailed explanation:

  • Handling user input (io::stdin().read_line()):
    • Reads input as a string, which is then trimmed to remove extra spaces and newlines
    • Used for both numbers and the operation selection
  • Validating numeric input (the get_number() function):
    • Uses a loop to repeatedly ask the user for input until a valid number is provided
    • parse::<f64>() converts the input string into a floating-point number
    • If the input is not a number, it prints an error message and retries
  • Using match for decision-making:
    • Determines which arithmetic operation to perform
    • Prevents division by zero, an important safety check
    • Returns None for invalid operations, preventing incorrect calculations
  • Displaying the result (if let Some(res) = result):
    • If a valid result exists (Some(value)), it prints it
    • If an error occurred (e.g., invalid operation, division by zero), no incorrect result is shown

Step 3: Running the program

Now, compile and run your calculator:

cargo run

Try entering different numbers and operations. If you enter invalid input, the program will prompt you until a valid number is provided.

What you learned

This simple CLI calculator introduced several fundamental Rust concepts:

  • Handling user input using std::io::stdin()
  • Using functions to keep the code modular and readable
  • Error handling with match expressions and loops for input validation
  • String parsing and working with numbers using .trim() and .parse()

This is just the beginning! Don’t worry if you don’t understand everything now; this was meant to give you an idea of what Rust code looks like and to help you become familiar with the Rust syntax!

CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
The Rust Programming Handbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon