Getting Started With Rust: Your First Program and Why Cargo Changes Everything
Not a medium member ? Read it here
Welcome back to Zero to Rust! In our previous lesson, we laid the groundwork for understanding Rust’s philosophy. Now, it’s time to get our hands dirty and write some code! By the end of this lesson, you’ll have Rust installed, your first Rust program running, and a solid understanding of fundamental syntax and data types. Let’s get started!
Step 1: Installing Rust and Cargo — Your Toolkit
Rust comes with a powerful package manager and build system called Cargo. We’ll install both using rustup, the official Rust installer.
1.1 Downloading and Installing Rust:
rustup makes installation a breeze across different operating systems.
For Windows:
- Download the Rust installer from rust-lang.org.
- Run the installer (
rustup-init.exe) and follow the on-screen instructions. - Restart your terminal or command prompt.
- Verify installation with:
rustc --version
rustc --version
For macOS/Linux:
- Open a terminal and run the following command:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
-
Follow the installation prompts.
-
Restart your terminal.
-
Verify installation:
rustc --version
rustc --version
If everything is installed correctly, you should see Rust’s version number.
1.2 Understanding Cargo:
Cargo is your best friend in the Rust ecosystem. It handles everything from project creation and dependency management to building and running your code. rustup installs Cargo automatically, so you’re already set!
Step 2: Setting Up Your Development Environment
While you can write Rust code in any text editor, a good IDE (Integrated Development Environment) can significantly boost productivity. Here are some recommended options:
- VS Code: A popular and lightweight editor. Install the
rust-analyzerextension for excellent code completion, diagnostics, and formatting. This is highly recommended for Rust development. - IntelliJ IDEA/CLion: If you prefer a more full-featured IDE, both IntelliJ IDEA (with the Rust plugin) and CLion offer great Rust support.
For this tutorial, VS Code with rust-analyzer will be our suggested environment.
Step 3: Creating Your First Rust Project
Let’s create a simple “Hello, world!” project.
- Creating a New Project: Open your terminal and navigate to the directory where you want to create your project. Then, run the following command:
cargo new hello_world
cd hello_world
cargo new hello_world
cd hello_world
This command does two things:
cargo new hello_world: Creates a new directory namedhello_worldcontaining a basic Rust project structure.cd hello_world: Changes your current directory to the newly created project directory.
- Exploring the Project Structure: Inside the
hello_worlddirectory, you’ll find:
hello_world/ ├── Cargo.toml # Project metadata and dependencies └── src/ └── main.rs # Entry point
hello_world/ ├── Cargo.toml # Project metadata and dependencies └── src/ └── main.rs # Entry point
Cargo.toml is the manifest file for your project. It’s where you’ll manage dependencies and other project settings. src/main.rs contains the source code for your program.
- Running the Project: Now, let’s run our “Hello, world!” program:
cargo run # Compiles and executes the code
cargo run # Compiles and executes the code
Cargo will compile your code and execute it. You should see the following output in your terminal:
Hello, world!
Hello, world!
4. Examining main.rs: Open src/main.rs in your text editor. You’ll see the following code
fn main() { println!("Hello, world!"); }
fn main() { println!("Hello, world!"); }
Let’s break it down:
fn main(): This defines the main function, which is the entry point of every Rust program. Execution always begins here.
println!(“Hello, world!”);: This line prints the string “Hello, world!” to the console. println! is a macro (indicated by the !), which is a special type of function in Rust.
Step 4: Rust Syntax Basics — Building Blocks
Now that you’ve run your first Rust program, let’s explore some fundamental Rust syntax.
4.1 Variables and Mutability:
- Immutability by Default: In Rust, variables are immutable (cannot be changed) by default. This helps prevent accidental modifications and makes your code more predictable.
let x = 5; // x = 6; // Error: cannot assign twice to immutable variable
let x = 5; // x = 6; // Error: cannot assign twice to immutable variable
- Making Variables Mutable: To make a variable mutable, use the
mutkeyword:
let mut y = 5; y = 10; // Allowed
let mut y = 5; y = 10; // Allowed
- Shadowing: You can declare a new variable with the same name as an existing one. This is called shadowing. The new variable “shadows” the old one. Importantly, the shadowed variable can even have a different type!
let z = 5; let z = z + 1; // New variable, same name (type can change!)
let z = 5; let z = z + 1; // New variable, same name (type can change!)
4.2 Data Types:
Rust is a statically typed language, which means the type of each variable is known at compile time. Rust often infers types automatically, but you can also explicitly specify them.
- Scalar Types: These represent single values.
- String Type: The String type is used for storing growable, mutable text. It’s different from the primitive string slice (&str) which you’ll encounter in the next article. Think of String as owning its text data, allowing it to be modified.
let message: String = String::from("Hello, Rust!"); // Creating a String
let name = "Alice"; // This is a &str (string slice)
// You can modify a String:
let mut greeting = String::from("Hello, ");
greeting.push_str(name); // Appends the &str "Alice"
greeting.push_str("!");
println!("{}", greeting); // Output: Hello, Alice!
// You can also create a String from a &str:
let name_string = name.to_string(); // Now name_string is a String
// &str are immutable fixed length string slices.
// String are growable, mutable, owned strings.
/* Plus this is how to comment the whole paragraph /*content/code*/
Explaination :
String::from(): This is a common way to create a String from a
string literal (&str).
push_str(): This method allows you to append a string
slice (&str) to a String. This demonstrates
the mutability of String.
to_string(): This method converts a string slice (&str)
to a String.
The key distinction between String and &str is ownership.String owns its
data, which means it can be modified. &stris a "view" into existing
string data (whether it's owned by a String or is a string literal)
and cannot be modified directly. This will be explored in more detail
when ownership and borrowing are covered.
*/
let message: String = String::from("Hello, Rust!"); // Creating a String
let name = "Alice"; // This is a &str (string slice)
// You can modify a String:
let mut greeting = String::from("Hello, ");
greeting.push_str(name); // Appends the &str "Alice"
greeting.push_str("!");
println!("{}", greeting); // Output: Hello, Alice!
// You can also create a String from a &str:
let name_string = name.to_string(); // Now name_string is a String
// &str are immutable fixed length string slices.
// String are growable, mutable, owned strings.
/* Plus this is how to comment the whole paragraph /*content/code*/
Explaination :
String::from(): This is a common way to create a String from a
string literal (&str).
push_str(): This method allows you to append a string
slice (&str) to a String. This demonstrates
the mutability of String.
to_string(): This method converts a string slice (&str)
to a String.
The key distinction between String and &str is ownership.String owns its
data, which means it can be modified. &stris a "view" into existing
string data (whether it's owned by a String or is a string literal)
and cannot be modified directly. This will be explored in more detail
when ownership and borrowing are covered.
*/
- Integers:
i32(32-bit signed integer, the default integer type),u8(8-bit unsigned integer),i64(64-bit signed integer), etc.
let a: i32 = 10; // 32-bit signed integer (default type is i32)
let b: u8 = 255; // 8-bit unsigned integer
let a: i32 = 10; // 32-bit signed integer (default type is i32)
let b: u8 = 255; // 8-bit unsigned integer
- Floating-Point Numbers:
f32,f64(64-bit floating-point, the default floating-point type).
let c: f64 = 3.14; // 64-bit floating point (default type is f64)
let d: f32 = 2.5; // 32-bit floating point
let c: f64 = 3.14; // 64-bit floating point (default type is f64)
let d: f32 = 2.5; // 32-bit floating point
- Boolean:
bool(true or false).
let is_rust_fun: bool = true;
let is_rust_fun: bool = true;
- Character:
char(represents a single Unicode character, 4 bytes).
let letter: char = 'A';
let letter: char = 'A';
- Compound Types: These can hold multiple values.
- Tuples: Fixed-length, ordered collections of values of potentially different types.
let tup: (i32, f64, char) = (500, 6.4, 'A');
let (x, y, z) = tup; // Destructuring: Accessing elements of the tuple
println!("x: {}, y: {}, z: {}", x, y, z);
println!("tup.0: {}, tup.1: {}, tup.2: {}", tup.0, tup.1, tup.2); // Accessing by indexArrays: Fixed-length, homogeneous.
let tup: (i32, f64, char) = (500, 6.4, 'A');
let (x, y, z) = tup; // Destructuring: Accessing elements of the tuple
println!("x: {}, y: {}, z: {}", x, y, z);
println!("tup.0: {}, tup.1: {}, tup.2: {}", tup.0, tup.1, tup.2); // Accessing by indexArrays: Fixed-length, homogeneous.
- Arrays: Fixed-length, ordered collections of values of the same type.
let arr = [1, 2, 3, 4, 5];
let first = arr[0]; // Accessing the first element (index 0)
println!("first: {}", first);Functions
let arr = [1, 2, 3, 4, 5];
let first = arr[0]; // Accessing the first element (index 0)
println!("first: {}", first);Functions
4.3 Functions:
- Naming Convention: Use snake_case for function names (e.g.,
my_function,another_function). - Parameters and Return Values:
i32 {
a + b // No semicolon here means this is the return value
}
let sum = add(5, 3);
println!("Sum: {}", sum);” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn add(a: i32, b: i32) -> i32 {
a + b // No semicolon here means this is the return value
}
let sum = add(5, 3);
println!("Sum: {}", sum);
fn add(a: i32, b: i32) -> i32 {
a + b // No semicolon here means this is the return value
}
let sum = add(5, 3);
println!("Sum: {}", sum);
- Statements vs. Expressions:
- Statements: Perform actions but don’t return a value (e.g.,
let x = 6;). - Expressions: Evaluate to a value (e.g.,
x + 1,{ let y = 5; y + 1 }).
Notice how a block of code enclosed in curly braces can be an expression.
4.4 Control Flow:
ifExpressions:
let number = 6;
if number % 2 == 0 {
println!("Even");
} else {
println!("Odd");
}Loops:
let number = 6;
if number % 2 == 0 {
println!("Even");
} else {
println!("Odd");
}Loops:
Note: No parentheses are needed around the condition in an
ifexpression.
- Loops:
whileLoop:
<button data-code="let mut counter = 0;
while counter
let mut counter = 0;
while counter < 5 {
println!("Counter: {}", counter);
counter += 1;
}
let mut counter = 0;
while counter < 5 {
println!("Counter: {}", counter);
counter += 1;
}
loop(Infinite Loop):
loop {
println!("Press Ctrl+C to stop!");
}
loop {
println!("Press Ctrl+C to stop!");
}
Key Syntax Recap:
- Variables: Default to immutable. Use
mutto make them mutable. - Types: Rust has simple types like integers, booleans, and characters, and compound types like tuples and arrays.
- Functions: Functions are defined with
fnand return values automatically unless the function has a semicolon. - Control Flow: Use
if,while, andloopto make decisions and repeat actions.
Step 5: Key Takeaways
- Immutability: Variables are immutable by default; use
mutto change. - Type Safety: Rust enforces type checks at compile time.
- Expressions Matter: Code blocks and functions return values.
- Cargo Commands:
cargo new: Create a project.cargo build: Compile.cargo run: Compile and run.cargo check: Validate code without compiling.
Practice Exercise
Write a function is_divisible(num: i32, divisor: i32) -> bool that checks if num is divisible by divisor. Test it in main().
bool {
num % divisor == 0
}
fn main() {
println!("Is 10 divisible by 3? {}", is_divisible(10, 3));
}
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
fn is_divisible(num: i32, divisor: i32) -> bool {
num % divisor == 0
}
fn main() {
println!("Is 10 divisible by 3? {}", is_divisible(10, 3));
}
fn is_divisible(num: i32, divisor: i32) -> bool {
num % divisor == 0
}
fn main() {
println!("Is 10 divisible by 3? {}", is_divisible(10, 3));
}
Next Lesson Preview
In Lesson 3, we’ll explore ownership, borrowing, and slices — Rust’s features for memory safety. You’ll learn why Rust doesn’t need a garbage collector and how to avoid common pitfalls.
Follow this series and join us in mastering Rust from scratch!
Reach out here on Linkedin


