Frank Perez

Frank Perez

Keep in touch

An experienced Web Developer with years of experience in design, programming and server administration.

Blog

Overview

© 2024 by Frank Perez.

Starting with Rust: From Installation to Your First Program

This guide will walk you through installing Rust and writing your first "Hello, world!" program. By the end, you'll have a foundational understanding of the Rust toolchain and the Cargo.toml file's significance.

Installing Rust

The first step to starting with Rust is to install the Rust toolchain. This includes rustc (the compiler), cargo (the package manager and build tool), rustfmt (the code formatter), and rustup (the Rust toolchain installer and version management tool).

  1. Rustup: The easiest way to install these components is through rustup, which manages Rust versions and associated tools. To install rustup, visit the official Rust website and follow the instructions for your operating system.

  2. Verify Installation: Once installed, open a terminal or command prompt and enter the following command to verify that rustc and cargo are installed:

    rustc --version
    cargo --version

Writing Your First "Hello, World!" Program

With Rust installed, it's time to write your first Rust program.

  1. Create a New Project: Open a terminal and run the following cargo command to create a new Rust project:

    cargo new hello_rust

    This command creates a new directory called hello_rust with a basic project structure.

  2. Explore the Project Structure: Navigate into your project directory by cd hello_rust. You'll see two main files:

    • Cargo.toml: This file is the heart of your project's configuration. It defines your package, dependencies, and other metadata.
    • src/main.rs: This is your main source file where your Rust code lives.
  3. The Cargo.toml File: Open the Cargo.toml file. Notice how it specifies the package name, version, authors, and more. Cargo uses this file to manage your project's dependencies and build settings.

  4. Writing the Program: Open the src/main.rs file. By default, it contains a simple "Hello, world!" program:

    fn main() {
     println!("Hello, world!");
    }
  5. Running Your Program: Back in the terminal, run the following command from your project directory:

    cargo run

    This command compiles and runs your program, printing "Hello, world!" to the console.

Understanding the Rust Toolchain

  • rustc: The Rust compiler, responsible for compiling Rust code into binary executables.
  • cargo: Rust's package manager and build tool, handling dependencies, compiling packages, and more.
  • rustfmt: Automatically formats Rust code according to style guidelines, ensuring consistent code style.
  • rustup: Manages Rust versions and associated tools, allowing you to easily switch between stable, beta, and nightly Rust.
  • rust-analyzer: An optional tool (usually an IDE plugin) that provides advanced code analysis and editor support for Rust.