Written By :

Category :

Ops

Posted On :

Share This :

Learning RUST: An easy step by step guide

Introduction

Rust is a modern programming language that is focused on safety, speed, and concurrency. It is a systems programming language that is designed to be fast, safe, and concurrent. It is a great choice for many types of projects, including systems programming, embedded systems, and game development.

Rust Lang
Rust Lang

In this tutorial, we will cover the basics of Rust programming, including variables, data types, control flow, functions, and more. We will also provide examples of code and their outputs to help you understand the concepts better.

Getting Started

Before you can start programming, you need to have the tools installed on your computer. You can download and install from the official website: https://www.rust-lang.org/tools/install. Check out our BASH post for more help on BASH.

Once the tools are installed, you can start writing your first program. You can use any text editor or IDE to write your code.

Hello World

The first program that most programmers write in any new language is the “Hello World” program. Here is an example of a “Hello World” program in Rust:

fn main() {
    println!("Hello World Rust Tutorial Step 1!");
}

You can run this program by saving it to a file named main.rs and then running the following command in your terminal:

$ rustc main.rs
$ ./main

Output :

Hello World Tutorial Step 1!

Variables

In Rust, variables are immutable by default. This means that once a variable is assigned a value, it cannot be reassigned a new value. If you want to be able to reassign a variable, you need to use the keyword let mut.

Here is an example of declaring and reassigning a variable in Rust:

let x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);

Output :

error: re-assignment of immutable variable `x`
  --> main.rs:3:5
   |
2  |     let x = 5;
   |         - first assignment to `x`
3  |     x = 6;
   |     ^^^^ re-assignment of immutable variable

To make it mutable:

let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);

Output:

The value of x is: 5
The value of x is: 6

Data Types

Rust has several built-in data types, including integers, floating-point numbers, booleans, and characters.

Here is an example of using some of the basic data types in Rust:

let x = 5; // Integer
let y = 3.14; // Float
let z = true; // Boolean
let a = 'A'; // Character

Control Flow

Rust has several control flow statements, including if, else, while, and for.

Here is an example of using an if statement in Rust:

let x = 5;

if x > 0 {
    println!("x is positive");
} else {
    println!("x is non-positive");
}

Similarly, you can use `while` and `for` loop like:

// while loop
let mut x = 5;
while x > 0 {
    println!("{}", x);
    x -= 1;
}

// for loop
for i in 0..5 {
    println!("{}", i);
}

Functions

Functions are blocks of code that can be called multiple times. In Rust, you can define a function using the fn keyword.

Here is an example of defining and calling a function in Rust:

fn add(x: i32, y: i32) -> i32 {
    x + y
}

let sum = add(5, 3);
println!("The sum is: {}", sum);

Package Manager

In Rust, packages are called crates and they are managed by the package manager called Cargo. Cargo is the official package manager for the Rust programming language, and it is used to manage dependencies, build and compile code, and more.

Here are the basic steps for working with crates in Rust:

  1. Create a new project: To create a new Rust project, you can use the command cargo new <project-name>. This will create a new directory with the given name, and it will contain a basic project structure, including a Cargo.toml file.
  2. Add dependencies: To add dependencies to your project, you can edit the Cargo.toml file and add the desired crates under the [dependencies] section. For example, to add the serde crate, you would add the following line to the Cargo.toml file: serde = "1.0".
  3. Build and run the project: Once you have added the dependencies to your project, you can use the command cargo build to build the project, and cargo run to run the project. Cargo will automatically download and install the dependencies specified in the Cargo.toml file.
  4. Publish a Crate: If you want to share your crate with others, you can publish it to crates.io, the official Rust package registry. To publish your crate, you will need to create an account on crates.io, then use the cargo login command to log in, and finally use the cargo publish command to publish your crate.
  5. Update dependencies: To update the dependencies of your project, you can use the command cargo update. This will update all the dependencies in the project to their latest version.
  6. Remove a dependency: To remove a dependency from your project, you can simply remove the corresponding line from the Cargo.toml file, then use the command cargo update to remove the dependency from the project.

By using Cargo, you can easily manage dependencies, build and run your projects, and share your crates with others. It makes the process of working with crates in Rust more efficient and manageable.

An example cargo.toml file would look something like this:

[package]
name = "new-project
version = "0.1.0"
authors = ["Your Name <your@email.com>"]

[dependencies]
reqwest = "0.11.13"
tokio = "1.21.2"
serde = "1.0.152"

Setting up VSCode

Setting up a development environment for Rust in Visual Studio Code (VSCode) can be a bit of a challenge, especially for those new to the language. However, with a few simple steps, you can have a fully functional development environment up and running in no time.

Here are the steps to set up a VSCode development environment for Rust on Linux:

  1. First, you will need to install Rust on your system. You can do this by running the following command in a terminal:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  1. Once Rust is installed, you will need to install the rust-analyzer extension for VSCode. This extension provides a number of features such as code completion, linting, and more. You can install it by opening the Extensions pane in VSCode and searching for “rust-analyzer”.
  2. Next, you will need to install the Rust Language Server (RLS). This is a separate tool that provides additional functionality such as code navigation and refactoring. You can install it by running the following command in a terminal:
rustup component add rls-preview rust-analysis rust-src
  1. Once the RLS is installed, you will need to configure VSCode to use it. To do this, open the Settings editor in VSCode (File > Preferences > Settings or by using the keyboard shortcut Ctrl + ,) and add the following setting:
"rust-analyzer.serverPath": "rls"
  1. You will also need to install the Cargo extension in VSCode. This extension provides integration with the Cargo package manager for Rust. You can install it by searching for “Cargo” in the Extensions pane.
  2. Finally, you can create a new Rust project by running the following command in a terminal:
cargo new my-project

And then open the folder in vscode.

Here are the steps to set up a VSCode development environment for Rust on Windows:

  1. First, you will need to install Rust on your system. You can do this by downloading the installer from the official website and running it.
  2. Once Rust is installed, you will need to install the rust-analyzer extension for VSCode. This extension provides a number of features such as code completion, linting, and more. You can install it by opening the Extensions pane in VSCode and searching for “rust-analyzer”.
  3. Next, you will need to install the Rust Language Server (RLS). This is a separate tool that provides additional functionality such as code navigation and refactoring. You can install it by running the following command in Command Prompt or PowerShell:
rustup component add rls-preview rust-analysis rust-src

Once the RLS is installed, you will need to configure VSCode to use it. To do this, open the Settings editor in VSCode (File > Preferences > Settings or by using the keyboard shortcut Ctrl + ,) and add the following setting:

"rust-analyzer.serverPath": "rls.exe"

You will also need to install the Cargo extension in VSCode. This extension provides integration with the Cargo package manager for Rust. You can install it by searching for “Cargo” in the Extensions pane.

Finally, you can create a new Rust project by running the following command in Command Prompt or PowerShell:

cargo new my-project

And then open the folder in vscode.

With these steps, you should now have a fully functional development environment for Rust in VSCode. You can now start writing and running Rust code, and take advantage of all the features provided by the rust-analyzer and Cargo extensions, as well as the Rust Language Server.

Note: It’s also recommended to install the “Rust (rls)” extension for VSCode, to enable features such as go-to-definition, hover-over information, and more.

How does Rust compare to Python performance wise?

It is difficult to give a specific percentage of how much faster Rust is compared to Python, as it can vary greatly depending on the specific task and use case.

In general, Rust programs tend to be faster than Python programs, especially for tasks that require low-level control over memory and threading. However, the performance difference can vary greatly depending on the specific task and how the code is implemented.

For certain numerical computation tasks, Rust can be several times faster than Python due to its low-level control over memory, which can be leveraged to achieve better performance. For example, benchmarks have shown that Rust can be up to 50 times faster than Python for certain machine learning tasks.

On the other hand, for certain tasks such as web development, the performance difference might not be as significant, since the overhead of the web framework or the database will be the main bottleneck.

It is important to note that performance is not the only factor that should be considered when choosing a programming language for a project. Other factors, such as ease of use, readability, maintainability, and community support, should also be taken into account.

10 Tips and Tricks for new Rust developers

  1. Start with the basics: Before diving into more advanced topics, make sure you have a solid understanding of the basics of Rust, including variables, data types, control flow, and functions.
  2. Learn about ownership and borrowing: Rust’s ownership and borrowing model is one of its key features, so it’s important to understand it well. Make sure you understand how ownership and borrowing work and how to use them effectively.
  3. Use the Rust documentation: Rust’s documentation is extensive and well-written, so make sure you use it as a resource. The documentation includes detailed explanations of Rust’s features and syntax, as well as examples and tutorials.
  4. Write tests: Writing tests is a good way to ensure that your code is working as expected. Rust has built-in support for testing, so make sure you use it.
  5. Use the Rust playground: The Rust playground is a great tool for experimenting with Rust code and seeing how it behaves. It allows you to write, compile, and run Rust code online, and you can share your code with others.
  6. Use the Rust error handling: Rust’s error handling is one of its key features, so it’s important to understand it well. Make sure you understand how to use the Result type, and how to handle errors in your code.
  7. Use the Rust standard library: Rust’s standard library is extensive and well-written, so make sure you use it as a resource. The standard library includes a wide variety of useful modules and functions that can save you time and effort.
  8. Learn about macro : Rust has powerful macro system which can help you write more readable and maintainable code.
  9. Make use of the Cargo: Rust’s package manager, Cargo, is a great tool for managing dependencies and building your projects. Make sure you understand how to use it effectively.
  10. Join the Rust community: Rust has a large and active community, so make sure you join it. You can ask questions, share your code, and get help from other Rust developers.

Check out Let’s Get Rusty on YouTube. I’ve found them to have a lot of useful information.

https://www.youtube.com/@letsgetrusty/videos

Keep in mind that Rust is a relatively new language and is constantly evolving, so it’s important to stay up to date with the latest features and best practices. With practice and persistence, you will be able to master Rust and use it to build robust and efficient programs.

Conclusion

This tutorial provided a brief introduction to the Rust programming language, including its basic syntax, data types, control flow, and functions. As you continue to learn Rust, you will encounter more advanced features and concepts, such as error handling, traits, and ownership. There are also many resources available online to help you learn Rust, including the official Rust documentation, Rust books, and Rust tutorials. With practice and persistence, you will be able to master Rust and use it to build robust and efficient programs.

One response to “Learning RUST: An easy step by step guide”

  1. Jack Li Avatar
    Jack Li

    Good stuff! Keep them coming!

Leave a Reply