LanguagesAn Introduction to the Rust Programming Language

An Introduction to the Rust Programming Language

Since its launch in 2010, Rust has forged a path directly to the heart of the developer’s community, reaching the enviable top position among the most loved languages, according to the Stack Overflow Developer Surveys.

Part of that success is the language’s flexibility: Rust can be used to create game engines, operating systems, file systems, browser components, websites and tools, and more.

In short, Rust is a static multi-paradigm programming language, more focused on performance and security. In practice, its usage resembles a lot of C++, being very light, simple, and fast.

It was created by Graydon Hoare for Mozilla and later refined until it reached a stable version for release.

In this article, we’ll take some time to analyze the language at its very introductory topics. Let’s go!

Why Use Rust?

Rust is really fast, to the point of almost reaching C++ performance numbers.

It plays very well with systems that require intense safety and concurrency by defining strong security barriers, ensuring the system’s protection at its core.

This focus on safety can be seen everywhere within Rust, from the syntax to the basic data structure definitions

For example, whenever you declare a variable in Rust, it is going to create it as a constant. Yes, you read that right! If you want that variable to be, well, variable… you’d have to explicitly say that to Rust.

Rust also worries a lot about memory safety by not allowing, for example, null pointers. When it comes to data values, you can only initialize them via a bunch of predefined ways (all of which require a default value to work).

Regarding garbage collection, none of the common systems used by Java or C# is adopted by Rust. It, instead, makes use of a convention called Resource acquisition is initialization (RAII) on which the references to the objects, disk space, etc., are kept stored in a specific part of the memory and auto managed by Rust whenever the memory needs to be emptied.

Set Up & Hello World

If you just want to test it out without installing it, Rust offers an online playground for that.

Otherwise, just follow the instructions on the Install page. You only need a single command for that:

curl –proto ‘=https’ –tlsv1.2 -sSf https://sh.rustup.rs | sh

Once you enter the Playground page, you see a Hello World example already there:

fn main() {

    println!(“Hello, world!”);

}

It’s nice to have that when getting started, since it demonstrates the basic structure of a Rust program:

  • You need a main function, like many other languages;

  • Each function is preceded by the identifier fn;

  • To print something to the default system’s output, use the println! function.

You should see a result like the one below:

Hello world Rust

Figure 1: “Hello World” in Rust Playground

What About Rust Syntax?

The syntax resembles a mix between JavaScript, Ruby, and Kotlin. Depending on the familiarity you have with other major languages, it’s like Rust has taken a bit (the good bits, by the way) from each one and composed a new language syntax.

As you’ve seen before, the execution starts at the main function. We also talked about the immutability of Rust’s variables, so let’s take the following example:

fn main() {

    let a = 0;

    a = a + 1;

    println!(“The value of a is: {}”, a);

}

Here, we’re declaring a new variable (through the let operator, just like in JavaScript), with zero and a line after, incrementing its value by one. Note how the code also prints a concatenated value via the {} operators.

Rust will simply print an error to the console:

Rust console error

Figure 2: Rust console error

For the above example to work, you’d have to explicitly make the variable mutable:

let mut a = 0;

You can also determine the type a variable may have. Take this next example:

fn main() {

    let age: u32 = 12;

    let account_balance: f32 = -12.5;

    let char_a: char = ‘A’;

    let is_right: bool = false;

    let name: &str = “Bla Bla”;

    let _name2 = String::from(“Bla Bla 2”);

    let ids: [i32; 2] = [-1, 2];

    println!(

        “{}, {}, {}, {}, {}, {:?}”,

        age, account_balance, char_a, is_right, name, ids

    );

}

This should be the output:

2, -12.5, A, false, Bla Bla, [-1, 2]

Some important points:

  • The first line shows how to declare and instantiate a variable, as well as define its type. You can check the list of all the available types here

  • Rust prefers that its variables and functions be named under the snake case pattern

  • Within the integer type, there are two others: the ones starting with i (for signed integers, i.e., an integer that carries a sign with it) and the ones starting with u (for unsigned integers)

  • A string can be either a native type (&str) or an object (String). You can see both ways to create a string

  • When you create variables that possibly won’t be used, Rust recommends the variable name to start with an underline character

  • An array can have its elements typed as well; you only need to determine the type preceded by the number of elements.

If you make use of any variable without initializing it (let’s say age), Rust will also throw an error stating so:

Rust variable error

Figure 3: Rust error when trying to access an uninitialized variable

Managing Dependencies in Rust

Every major language and platform needs to have its registry, a place where the open source community can create new dependencies, publish freely and allow other users to easily download and use them alongside their projects.

Rust’s default dependency manager is called cargo, which, in turn, comes with an online registry called crates.

An external dependency can be easily added as follows:

use rand::Rng;

fn main() {

    let mut rng = rand::thread_rng();

    let number = rng.gen_range(0, 100);

    println!(“Random number: {}”, number);

}

The rand package belongs to the Rust crate’s core. So it can just be imported and used right away. In the example, we’re generating a random number between 0 and 100 and printing it.

These packages, however, may be needed in real projects, which can be generated through the cargo’s commands.

Give Rust a Try!

This piece is, obviously, just a small intro into the Rust universe. I can’t stress enough the need for a thorough reading of the official docs to get a deeper understanding of what the language is capable of.

Rust has proven its value throughout the last 10 years and is more than ready for a place within your project’s tools, so give it a try!

 

 

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories