Approx. read time: 7.9 min.

Post: Beginning Your Rust Programming Odyssey

Beginning Your Rust Programming Odyssey – Embarking on Your Rust Adventure

Kickstart your journey with Rust—a comprehensive yet intricate programming language. This guide covers the essentials:

Installation Essentials

Initiating your Rust adventure begins with the installation process. We utilize rustup, a robust tool for managing Rust versions and tools. This necessitates an active internet connection.

Attention: If rustup doesn’t fit your needs, explore alternative installation methods at the Rust Forge’s dedicated page for more options.

Adhering to the instructions below installs Rust’s latest stable release. Thanks to Rust’s stability promise, examples presented here will remain valid and compile with newer Rust versions, though output may slightly vary as Rust continuously enhances error messages and warnings.

Command Line Insights

Throughout this guide and the broader lessons, we’ll present terminal commands—commands to be executed are prefixed with $ (for Unix-like systems) or > (PowerShell for Windows), symbolizing the command prompt. The $ or > is not to be typed; it merely indicates the start of a command. Outputs from these commands typically follow without a prefix.

Installing Rust with rustup on Linux/macOS

Linux or macOS users can install Rust by executing the following in the terminal:

$ curl --proto '=https' --tlsv1.3 https://sh.rustup.rs -sSf | sh

This command fetches and runs a script to install rustup and Rust’s latest stable version. During the process, you might be prompted to enter your password. Successful installation ends with a congratulatory message.

A linker, which Rust utilizes to compile its outputs into a single file, is also necessary. Most systems already have one. If you encounter linker errors, installing a C compiler, which typically includes a linker, is recommended. For macOS users, Xcode’s command line tools can be installed with:

$ xcode-select --install

Linux users might prefer GCC or Clang, depending on their distribution’s guidelines.

Rust Installation on Windows

Windows users should navigate to the Rust official installation page and follow the provided instructions. The process involves installing MSVC build tools from Visual Studio 2013 onwards. This requires downloading Visual Studio 2022, selecting “Desktop Development with C++,” the Windows 10 or 11 SDK, and the English language pack, among any others desired.

Troubleshooting Installations – Beginning Your Rust Programming Odyssey

Verify Rust’s successful installation by checking the version with the following command:

$ rustc --version

If successful, you’ll see Rust’s version, commit hash, and commit date. Failure to see this information means checking your system’s PATH variable or seeking assistance from the Rust community page.

Upkeep: Updating and Uninstalling Rust

Rust and rustup updates are streamlined through:

$ rustup update

Uninstalling is equally straightforward:

$ rustup self uninstall

Rust installations include local documentation accessible via rustup doc.

Diving into “Hello, World!” – Beginning Your Rust Programming Odyssey

Writing your first Rust program is a milestone. Following tradition, we’ll start with a “Hello, world!” program.

This tutorial assumes basic command line familiarity. Rust’s flexibility means your code can reside anywhere, and while many IDEs support Rust through rust-analyzer, this guide focuses on command-line interactions.

Project Setup

Begin by creating a project directory. This guide suggests a projects directory in your home folder.</ p>

Linux, macOS, and Windows PowerShell:

$ mkdir ~/projects
$ cd ~/projects
$ mkdir hello_world
$ cd hello_world

Windows CMD users should adjust the commands to use %USERPROFILE%.

Crafting and Executing a Rust Program

Create a new file named main.rs. Rust files end with .rs. Insert the following code into main.rs:

fn main() {
    println!("Hello, world!");
}

Compile and run this code in your terminal. Linux and macOS users can compile with rustc main.rs and execute with ./main. Windows users should use .\main.exe.

Understanding Rust Program Structure

The main function is pivotal, serving as the entry point for Rust executables. The function body, enclosed in curly braces, contains the core logic. Rust’s conventions include using four spaces for indentation and adhering to a standard style facilitated by rustfmt.

The example program uses println!, a macro, to print “Hello, world!” to the console. Each statement ends with a semicolon.

Compiling and Running: Two Distinct Steps

Before execution, Rust programs must be compiled with rustc. The compilation output is an executable file, placed in the current directory or a designated build directory. Running the executable then displays “Hello, world!”.

Introducing Cargo: Rust’s Build System and Package Manager

Cargo simplifies project management, automates builds, and manages dependencies. Starting a Rust project with Cargo makes adding dependencies effortless as your project grows.

To verify Cargo’s installation:

$ cargo --version

Starting a New Project with Cargo

Create a new project by running cargo new hello_cargo, generating a standard project structure with a Cargo.toml configuration file and a src directory containing main.rs.

Cargo’s Build and Execution Process

Building and running a Cargo-based project involves commands like cargo build and cargo run, streamlining the compilation and execution process. Cargo’s efficiency shines with larger projects, offering a consistent development experience across different platforms.

Releasing with Cargo

For release builds, use cargo build --release to optimize your code. Cargo places the optimized executable in target/release.

Conclusion

You’ve taken the first steps in Rust, learning to install Rust, use rustc and Cargo, and write a simple “Hello, world!” program. The upcoming article we will delve into more complex projects and Rust’s powerful features. Stay tuned for an engaging journey into Rust programming!

Creating a Guessing Game with Rust

Dive into Rust with a practical project that introduces several fundamental Rust concepts, including let, match, methods, associated functions, and external crates, to name a few. This project serves as a hands-on introduction, with a deeper exploration of these concepts to follow in subsequent articles. For now, the focus is on applying basic principles.

We’ll develop a classic introductory programming challenge: a guessing game. The essence of the game is straightforward: the application generates a random number between 1 and 100 and prompts the player to guess the number. The application will then inform the player if their guess is too low or too high. A correct guess results in a congratulatory message, and the game ends.

Initiating a New Project Start by creating a new project in your projects directory established in our first app, using Cargo with the following commands:

$ cargo new guessing_game
$ cd guessing_game

Upon execution, cargo new creates a new project named guessing_game, and the subsequent command navigates into the project directory. Inspect the automatically generated Cargo.toml file:

Cargo.toml

[package]
name = "guessing_game"
version = "0.1.0"
edition = "2021"
[dependencies]

Cargo, by default, generates a basic “Hello, world!” program. See this in the src/main.rs file and compile and run it seamlessly with cargo run.

Implementing the Guessing Game The game begins by requesting input from the player, processing said input, and ensuring it meets the expected criteria. Insert the following code into src/main.rs:

src/main.rs

use std::io;
fn main() {
println!("Guess the number!");
println!("Please input your guess.");

let mut guess = String::new();

io::stdin()
.read_line(&mut guess)
.expect(“Failed to read line”);

println!("You guessed: {guess}");
}

This segment introduces capturing user input using the io library and storing it within a variable. The process involves creating a mutable variable guess to hold the player’s input, with the io::stdin().read_line(&mut guess) method reading the input and appending it to guess. The program subsequently outputs the guess.

Variables and Mutability Variables in Rust are immutable by default. This behavior can be altered with the mut keyword, allowing for variable mutability. Here’s an illustration:

let apples = 5; // Immutable
let mut bananas = 5; // Mutable

Processing User Input To manage input, the io library is utilized, allowing for the reading of user input. This input is then processed and checked for its conformity to expected patterns.

Generating a Random Number For the game’s core, a secret number is randomly generated using the rand crate, not included in the Rust standard library but available through external crates.

Expanding Game Functionality The game evolves to compare the user’s guess against the secret number, providing feedback accordingly. This comparison leverages Rust’s match expressions and the Ordering enum to evaluate the guess against the secret number.

Enabling Multiple Guesses Implementing a loop allows the game to accept multiple guesses until the correct number is guessed, enhancing the game’s interactivity.

Improving User Experience To refine the game, input validation is introduced to handle non-numeric guesses gracefully, allowing the game to continue seamlessly.

Finalizing the Game The game concludes with the functionality to end the session upon a correct guess, coupled with the removal of the secret number’s disclosure to maintain the game’s challenge.

Conclusion This guessing game project provides a practical introduction to various Rust concepts such as variable mutability, control flow constructs, external crates, and more. The upcoming content will delve deeper into these topics, exploring Rust’s unique features and how they can be utilized to build efficient and safe applications.


Related Posts:

MediaCreationTool_Win11_23H2 – Create installation media for Windows 11(Opens in a new browser tab)

Create installation media for Windows(Opens in a new browser tab)

JavaScript Coding Interview Questions Guess the outputs of the following codes:(Opens in a new browser tab)

Rodge’s Electric Odyssey: A Journey Through the Beats of EDM(Opens in a new browser tab)

How to make a Go-Back Input button with inline JavaScript(Opens in a new browser tab)

About the Author: Bernard Aybout (Virii8)

I am a dedicated technology enthusiast with over 45 years of life experience, passionate about computers, AI, emerging technologies, and their real-world impact. As the founder of my personal blog, MiltonMarketing.com, I explore how AI, health tech, engineering, finance, and other advanced fields leverage innovation—not as a replacement for human expertise, but as a tool to enhance it. My focus is on bridging the gap between cutting-edge technology and practical applications, ensuring ethical, responsible, and transformative use across industries. MiltonMarketing.com is more than just a tech blog—it's a growing platform for expert insights. We welcome qualified writers and industry professionals from IT, AI, healthcare, engineering, HVAC, automotive, finance, and beyond to contribute their knowledge. If you have expertise to share in how AI and technology shape industries while complementing human skills, join us in driving meaningful conversations about the future of innovation. 🚀