Rust is a systems programming language created by Mozilla engineer Graydon Hoare in 2010. It emphasizes safety, performance, and concurrency, making it ideal for a wide range of applications.
Key Benefits of Rust:
Low-Level Control: Direct memory management with zero-cost abstractions,
rivaling C and C++.High-Level Productivity: Expressive syntax for building applications across
operating systems.Web Applications: Frameworks like Actix and Rocket enable robust web development.Rust has three release channels:
Stable: Production-ready, reliable version.Beta: Preview of the upcoming stable release, used for testing.Nightly: Built daily, includes experimental features but may be unstable.Rustup is the official tool for installing and managing Rust. It allows seamless switching between stable, beta, and nightly compilers and keeps them updated.
Installation Steps:
Windows Users:
macOS/Linux Users:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
Verify Installation:
Check that the Rust compiler (rustc) and package manager (cargo) are installed:
rustc --version
cargo --version
To start coding in Rust, you can use the Rust Playground, an online editor for testing code snippets. Rust Play Ground
Here’s a simple Hello World program in Rust:
fn main() {
println!("Hello, world!");
}
Explanation:
main(): main function is the entry point function in a rust programprintln!(): This is a macro. A macro that prints text to the console. Macros, denoted by !, are powerful metaprogramming tools that expand into code at compile time.Macros in Rust are defined using macro_rules! and allow code generation for
repetitive tasks. A macro is like a function. We can define the responsibility of the macro with a closure inside of it. Then we can call the macro to use it. Here’s an example of a simple macro:
macro_rules! sample_macro {
() => {
println!("Hello from the macro!");
};
}
You can use this macro in a program like this:
macro_rules! sample_macro {
() => {
println!("Hello from the macro!");
};
}
fn main() {
sample_macro!();
}
This macro takes no arguments and expands to print "Hello from the macro!" when invoked.
Semicolons in Rust separate expressions and are required after most statements, except for the last expression in a block, which implicitly returns its value. Omitting a semicolon on the last expression in a function allows it to return that value, a common Rust idiom. For example:
fn main() {
println!("Hello, world!"); // Semicolon required because of the marco
}
fn add(a: i32, b: i32) -> i32 {
a + b // Semicolon is optional here
}
Rust provides rustfmt, a tool for automatically formatting code to follow community style guidelines. Run it on your source file with:
rustfmt file_name.rs
What rustfmt Does:
To compile a Rust source file into an executable, use the Rust compiler:
rustc file_name.rs
What Compilation Produces:
.pdb file containing debugging information.To run the compiled program:
# on Unix-Like
./file_name
# on Windows
.\file_name.exe
Rust source files should follow snake_case (e.g., my_program.rs).
Cargo is Rust’s build system and package manager, included with the standard installation. It simplifies project creation, dependency management, and building.
Create a new project:
cargo new project_name_for_sample
Project Structure:
.git: Git repository for version control.src/: Directory containing source code (e.g., main.rs)..gitignore: Specifies files to ignore in version control.Cargo.toml: Configuration file for project metadata and dependencies.Cargo.tomlThe Cargo.toml file defines your project’s metadata and dependencies.
Here’s an example:
[package]
name = "hello_world_via_cargo"
version = "0.1.0"
edition = "2021"
[dependencies]
[package]: Specifies project name, version, and Rust edition.[dependencies]: Lists external libraries (crates) your project uses.Cargo supports two build modes:
./target/debug/cargo build
./target/release/cargo build --release
To build and run your project in one step:
cargo run
cargo run --release
If you just want a quick check to see if the code compiles correctly without any issues:
cargo check
Rust supports three primary types of comments:
///* and *//// for documenting items like functions, structs, and modules. These comments can be processed by documentation tools to generate user-friendly documentation.// Single-line Example:
let x = 5; // This variable holds the value 5
// Multi-line Example:
/*
This is a multi-line comment.
It can span multiple lines and is useful for longer explanations.
*/
let y = 10;
// Documentation Comments Example:
/// Adds two integers and returns the result.
///
/// # Examples
///
/// ```
/// let sum = add(5, 3);
/// assert_eq!(sum, 8);
/// ```
fn add(a: i32, b: i32) -> i32 {
a + b
}
/// A struct representing a point in 2D space.
struct Point {
x: f64, // The x-coordinate
y: f64, // The y-coordinate
}
Rust was created by Graydon Hoare in 2010 at Mozilla. It is used for systems programming and web applications due to its safety and performance.
rustfmt, formats Rust coderustc, compiles Rust coderustup, manages Rust versions and toolchainscargo, builds Rust projectsRustup is the official tool for installing and managing Rust versions and toolchains, allowing seamless switching between stable, beta, and nightly releases.
Rust has three release channels: Stable (production-ready), Beta (upcoming stable preview), and Nightly (daily builds with experimental features).
funcfndeffunctionThe fn keyword is used to define functions in Rust, as seen in the main function example.
The println! macro is used to print text to the console, and it is a macro, denoted by the ! symbol.
Running rustc --version and cargo --version confirms that the Rust compiler and Cargo are installed.
Rust source files use the .rs extension, and the main function is the entry point for Rust applications.
println! command classified as in Rust?println! is a macro in Rust, denoted by the ! symbol, used for printing to the console.
A macro in Rust is similar to a function, as it can take arguments and generate code, but it operates at compile time.
fn, fn print_val() { println!("Value"); }macro_rules!, macro_rules! print_val { () => { println!("Value"); }; }def, def print_val { println!("Value"); }macro, macro print_val() { println!("Value"); }Macros are defined using macro_rules!, and the example macro_rules! print_val { () => { println!("Value"); }; } correctly defines a macro that prints a value.
Macros in Rust are invoked using the macro name followed by !(), such as sample_macro!().
macro_rules! my_macro { () => { println!("Hello"); }; } and invoked as my_macro!();fn my_macro() { println!("Hello"); } and invoked as my_macro();macro my_macro { println!("Hello"); } and invoked as my_macro;def my_macro { println!("Hello"); } and invoked as my_macro();A macro is defined with macro_rules! and invoked with !(), as shown in the correct option.
Semicolons are required for most statements in Rust, but they are optional for the last expression in a block, which implicitly returns its value.
cargo formatrustc --formatrustfmt file_name.rscargo check --formatThe rustfmt file_name.rs command formats Rust code to follow community style guidelines.
Cargo is Rust’s package manager and build system, used for project creation, dependency management, and building.
cargo init project_namecargo new project_namecargo create project_namecargo start project_nameThe cargo new project_name command creates a new Rust project with a standard structure.
src/ folder, main.rs with main function, .git, Cargo.tomllib/ folder, lib.rs with init function, .gitignore, Cargo.locksrc/ folder, start.rs with start function, .git, Cargo.tomlcode/ folder, main.rs with main function, .gitignore, Cargo.tomlCargo creates a src/ folder with main.rs containing the main function, a .git repository, .gitignore, and Cargo.toml outside the folder.
The Cargo.toml file contains project metadata (name, version, edition) and dependencies under [package] and [dependencies].
cargo build --releasecargo runcargo buildcargo checkThe cargo build command builds a Rust project in debug mode by default.
cargo buildcargo build --releasecargo runcargo run --releaseThe cargo build --release command builds a Rust project in release mode, optimized for performance.
cargo build, Release: cargo build --releasecargo check, Release: cargo check --releasecargo start, Release: cargo start --releasecargo run, Release: cargo run --releasecargo run builds and runs in debug mode, while cargo run --release does so in release mode.
cargo buildcargo runcargo checkcargo testThe cargo check command verifies if the code compiles without generating an executable.