Rust programming language - Introduction

This is the seventh post of a serie where I’ll talk about some new programming languages with a nice future ahead. During this series I’ll explore deeper the Ceylon, Dart, Elixir, Rust and Swift 2 languages.

The plan is to make a post a week until December 15 (or maybe a little more) and spend 2 weeks exploring each one of them. In the first week I’ll explore the general aspects of the language and make some comparisons with other very known and established languages. In the post of the second week I’ll go deeper inside each one of the languages and explore the individual advantages on use them.

All the posts

  1. Ceylon Introduction
  2. Ceylon Usage
  3. Dart Introduction
  4. Dart Usage
  5. Elixir Introduction
  6. Elixir Usage
  7. Rust Introduction
  8. Rust Usage

Preface

There are hundred of programming languages out there. Which one should we use? Which help do we have to choose well? How do they compare to each other? This document is an attempt to provide some answers to these questions. Naturally, it would not be possible to provide complete answers: as I mentioned, there are too many programming languages. Nevertheless, we chose five languages with a potential to grow in importance in the coming years. These programming languages are Elixir, Rust, Dart, Swift and Ceylon. During this project, we shall be talking about each one of them. These discussions will be in breath, not in depth. Their goal is to provide the reader with the minimum of information necessary to compare them, and who knows, to lure one or other interested person in learning them in a greater level of details. In any case, we hope to contribute a bit to the popularization of these programming languages, which - likely - will be paramount to the development of computer science in the next ten years.

Rust

How did it appear?

Rust 1 is a general-purpose, multi-paradigm, compiled, systems programming language. Nowadays, the Rust project is maintained and developed by Mozilla 2 Research but it starts as a personal project by Mozilla employee Graydon Hoare 3 4.

Graydon starts working on Rust in 2006. He was already a engineer at Mozilla working on compilers and tools for other languages. He started sketching Rust thinking in a lot of obvious good ideas, known and loved in other languages, that haven’t made it into widely-used systems languages, or are deployed in languages that have very poor (unsafe, concurrency-hostile) memory models.

After working long time as a hobby project, he decided to show one such prototype he’d been working on his spare time to his manager. Mozilla took an interest and set up a team to work on this language as a component of longer-term project to rebuild their browser stack around safer, more concurrent, easier technologies than C++. That larger project is called “servo”. Mozilla is funding Rust development because of that.

Mozilla began sponsoring the project in 2009 and announced it in 2010. The first Rust compiler, that was written in OCaml 5, was dropped and rewritten in a Rust version that successfully compiled itself in 2011. It is called rustc and uses LLVM 6 as it’s back end. The version 1.0 7 was released in 15 May 2015.

Why was it designed and implemented?

System’s programming languages became widely used on the last 50 years since people started using high-level languages to write operating systems. Nevertheless, there were always two problems constantly present in this niche:

These are the problems that Rust was made to address. As it’s own creator says: Our target audience is “frustrated C++ developers” in which he includes himself. The performance of safe code (which is one of things that Rust aims) is expected to be slower than C++, however, the Rust program’s performance is comparable to C++ code that manually implements safer operations 9.

Rust is a compiled, multi-paradigm programming language. It supports pure-functional, actor-based concurrency, imperative-procedural and object-oriented programming styles.

How can we use it, e.g., install and run?

Linux and Mac OS

Rust has a simple installation proccess on Linux and Mac OS systems. Run the following line in the command terminal:

$ curl -sSf https://static.rust-lang.org/rustup.sh | sh

It will download the files, ask for sudo passwords and setup everything automatically.

Windows

There are binaries versions with installers for Windows users at the download page 10.

Testing the installation

Rust default toolset ships with a build tool called cargo 11. It is a tool to help manage the Rust projects. Cargo manages three things: building your code, downloading the dependencies your code needs, and building those dependencies.

To start a new project with cargo, run the command:

$ cargo new hello --bin

It will generate the dicrectory called hello with some files on it. On the directory root it creates a Cargo.toml file with some basic information about the project and a src directory with a main.rs file on it. This is the content of the main file:

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

To compile and run the project, in the project’s root directory, run the commands:

$ cargo build
   Compiling hello v0.1.0 (file:///home/taiar/dev/mono1/rust/hello)
$ cargo run
     Running `target/debug/hello`
Hello, world!

and the hello message just show up. The binary file is located at target/debug/hello and can be executed directly from the command line without the cargo tool too.

$ ./target/debug/hello
Hello, world!

Simple programs

Primitive types and mutability

Rust provides access to a wide variety of primitives:

Here are some usage:

fn main() {
    // Variables can be type annotated.
    let logical: bool = true;

    let a_float: f64 = 1.0;  // Regular annotation
    let an_integer   = 5i32; // Suffix annotation

    // Or a default will be used.
    let default_float   = 3.0; // `f64`
    let default_integer = 7;   // `i32`

    let mut mutable = 12; // Mutable `i32`.
}

Variables in Rust are immutable by default. The program:

fn main() {
    let truth = true;
    truth = false;
}

will result in a compile error:

error: re-assignment of immutable variable `truth` [E0384]

To be mutable, the variables must explicitly be annotated with mut:

fn main() {
    let mut lie = true;
    lie = false;
}

The version I’m using is Rust 1.5.0.

Object oriented programming

Rust uses structs to create more complex data types 12 13. For example, if we want to use two numbers to represent a point in the space:

struct Point {
    x: f32,
    y: f32,
}

fn main() {
    let mut point = Point { x: 0, y: 0 };

    point.x = 3;
    point.y = 4;
    
    println!("The point is at ({}, {})", point.x, point.y);
}

Rust also has the concept of Traits. A trait is a language feature that tells the Rust compiler about functionality a type must provide. If we want a method that tells the point distance to the origin:

use std::f32;

struct Point {
    x: f32,
    y: f32,
}

impl Point {
    fn distanceFromO(&self) -> f32 {
        f32::sqrt(self.x * self.x + self.y * self.y)
    }
}

fn main() {
    let point = Point { x: 3f32, y: 4f32 }; 
    println!("The distance from the origin is ({})", point.distanceFromO(), );
}

The Trait implements the distanceFromO method for the Point struct.

Visibility in Rust is done around modules. Rust provides a powerful module system that can be used to hierarchically split code in logical units (modules), and manage visibility (public/private) between them. A module is a collection of items: functions, structs, traits, impl blocks, and even other modules 14.

References

comments powered by Disqus