A quick introduction to Rust

Author: Theodore Odeluga

The source files for this project can be downloaded from here

After more than 30 years of stellar service, the grand old workhorse of professional software development, C++, now finds itself the subject of a lively discussion over its long-standing issue with memory safety.

In this regard, speculation continues around Rust, a relatively new multi-purpose programming language with similar capabilities – including the one feature C++ doesn’t have – automatic memory management – as a possible successor to the older language.

While JavaScript has its garbage collector and managing memory in C++ is largely down to a developer’s decision, Rust’s advantage stems from a set of rules based on “ownership” which automatically handle data capacity on a programmer’s behalf.

Irrespective of the arguments for and against, we know it’s always worth learning new tools and techniques which are likely to become important resources in future.

Any time we dedicate to the language therefore, will be well worth our while.

As C++ was back in the day, Rust is sometimes perceived as a bit of a difficult and obscure topic.

However, as we’ll see, apart from one or two differences in implementation, writing code with Rust is not so radically different from working with C++, C or Java.

With that in mind, this tutorial will be a quick, easy and straight-to-the-point introduction that’ll get you up and running as quickly as possible with an initial glimpse of the basics.

Programs can actually be written and executed fairly quickly in Rust and this is done in one of two ways.

Compilation can be achieved with nothing more than a simple instruction on the command line next to the name of the file in question.

Alternatively, a Cargo package can be used to build larger, more ambitious projects.

I’ll show you both methods in this primer.

Quick compilation

If you haven’t done so already, Rust’s installation requirements can be found here to set up your local environment.

After installation, you can compile a program in Rust like this:

1. Create a new folder at your root drive (i.e. - 'C' drive). Name the project folder after your program (or anything you like)

2. Create a new file in your text editor under your program name.

3. Write your code in the text file (as shown below with the example provided). Copy and paste it in its entirety and save it with the name factors.rs

Anyone familiar with C style languages will immediately see a few things they recognise in Rust’s syntax.

This is a simple program and certainly not ‘real-world’ but a nice start to getting used to the structure of a Rust program.

Note the variable references in curly braces embedded within the strings. This is similar to how data is used in templating languages like Jinja 2 for the Flask framework in Python.

fn main() {

let factor = 15; //Example
let multiple = 75; //Example
let result = multiple / factor;

if multiple - factor * result != 0 {
println!("{factor} is not a factor of {multiple}");
} else {
println!("{factor} is a factor of {multiple}");
println!("{factor} divides {multiple} {result} times");
    }
}

4. Once the file is saved, on the command line 'cd' or navigate the file path till you’re inside the project folder.

5. Once you’re in this location on the terminal type the following:

rustc factors.rs

Here’s an example of what your file path should look like at this stage.

In my setup, I’ve created a folder for all Rust projects in a directory structure on the root drive, then within that, sub-folders for each project.

i.e. - C:\Users\nameofyourcomputer\runrust\factortest> rustc factors.rs

6. Hit the Enter key.

Wait for the program to compile (The file path will reappear once compilation is finished (a small program like this will take just a few seconds)).

7. Now type the program name after the path with the .exe extension as in the following:

C:\Users\nameofyourcomputer\runrust\factortest> factors.exe

8. Hit the Enter key.

You should see the result and description of the factor test output to the command line. Congratulations – you’ve just compiled your first Rust program.

The ‘rustc’ command is used to invoke the Rust compiler and it’s written before the name of the file containing the Rust code with a .rs extension. Always use it when compiling or recompiling programs as outlined.

Build a Cargo package

As alluded to earlier, Rust projects which need additional classes and modules use the Cargo package manager.

Rust’s diverse ecosystem enables the creation and deployment of several different types of projects and Cargo is the gateway providing access to the many thousands currently in development. Similar to NPM for node.js, Cargo makes a wide choice available for valuable extensions, saving time while also improving productivity and code quality.

Setting up with Cargo is similar to the steps outlined above.

1. Set up a folder for the project if you haven’t done so already. Again, the best place for this is the root drive of your computer.

Example: C:\Users\nameofyourcomputer\myrustprojects>

2. As above, navigate (cd) till you’re inside the project folder on the command line.

3. While you're inside the folder, type the following:

cargo new [project name here (no square brackets of course)].

Cargo will create the project. You'll see something like the following appear just under the project file path.

Created binary (application) `mynewcargoproject` package

cd into the newly created project folder then enter the 'cargo run' command as below:

C:\Users\nameofyourcomputer\myrustprojects\mynewcargoproject> cargo run

(Make sure you're on the internet before you do this. Rust will automatically download all necessary dependencies and updates if required before running your project).

If you haven't edited or written your own code in the main.rs file located in the 'src' folder, Rust will create a generic 'hello world' program automatically included with each new cargo project and print those words to the screen.

When creating your own programs, you can remove this code and write your own in the main.rs file.

You can also create and add your own libraries once a package has been created. You simply reference the library or other dependency as follows under the dependencies section in the .toml file (also automatically created with each new Rust Cargo project).

The number after the equals sign is the version number which you need to include.

Example contents of a toml file:

[package]
name = "testcargo"
version = "0.1.0"
edition = "2021"

[dependencies]
mylibrary = "0.1.0"

Conclusion

You can learn more about 'crates' - or 'compilation units' to use the Rust technical term (Rust's name for programs) and the Cargo package system here: https://doc.rust-lang.org/cargo/guide/

This tutorial was a crash-course on the creation and procedure of Rust programs. To learn the language more deeply, you’ll of course need to practice further using additional code samples and read about the language’s architecture. The links below will help.

I hope you’ve enjoyed the introduction and I hope this brief article will add to your skillset, giving you even greater technical ability and freedom. Thanks for reading and happy coding.

Install Rust

https://www.rust-lang.org/

Learn Rust

https://www.rust-lang.org/learn

https://doc.rust-lang.org/book/

Code Examples

https://doc.rust-lang.org/rust-by-example/