Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Rust Basics

What is Rust?

Rust is a systems programming language that focuses on speed, memory safety, and parallelism. It was designed to enable developers to build reliable and efficient software. Rust’s unique features, such as its ownership model and rich type system, help prevent common programming errors, making it an excellent choice for both low-level systems programming and high-level application development.

Getting Started with Rust

To start programming in Rust, you need to install the Rust toolchain. The recommended way to install Rust is through rustup, which is an installer for the Rust programming language.

Installation Steps:

Open your terminal and run the following command:

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

Follow the on-screen instructions to complete the installation.

Once installed, you can verify your installation by checking the version of Rust:

rustc --version

Your First Rust Program

After setting up Rust, you can create your first Rust program. Rust programs are typically written in files with a .rs extension.

Let’s create a simple "Hello, World!" program:

Code Example:

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

To run this program, save it to a file named main.rs and use the following commands:

rustc main.rs
./main

The output will be:

Hello, World!

Basic Syntax and Data Types

Rust has a strong and static type system. Here are some of the basic data types:

  • Integers: Signed and unsigned integers, e.g., i32, u64.
  • Floating Point: For decimal numbers, e.g., f32, f64.
  • Boolean: Represents a true or false value.
  • Character: Represents a single Unicode character, e.g., 'a'.
  • Strings: A sequence of characters, e.g., "Hello".

Here’s an example of declaring variables of different types:

Code Example:

fn main() {
let integer: i32 = 10;
let float: f64 = 20.5;
let boolean: bool = true;
let character: char = 'R';
let string: &str = "Hello, Rust!";
}

Control Flow

Rust provides conditional statements and loops to control the flow of the program. Here are the basic control flow constructs:

  • If Statements: Used for conditional execution.
  • Loops: Used to repeat a block of code. Rust has loop, while, and for loops.

Here’s an example of using an if statement and a loop:

Code Example:

fn main() {
let number = 5;
if number < 10 {
println!("Number is less than 10");
}

for i in 0..5 {
println!("Value: {}", i);
}
}

Conclusion

Rust is a powerful language that combines safety and performance. Its unique features make it suitable for various programming tasks. In this tutorial, we covered the basics of Rust, including installation, syntax, data types, and control flow. As you continue to learn Rust, you'll discover even more features that will help you write robust and efficient code.