{{announcement.body}}
{{announcement.title}}

Discovering Rust

DZone 's Guide to

Discovering Rust

I like to read and practice different programming languages because they bring different visions and tools to solve problems. Today’s article is about discovering Rust.

· Web Dev Zone ·
Free Resource

Being a developer, it is easy to jump on the hype train and try to learn or even use in pet projects the latest libraries, frameworks and why not programming languages. In a sector where everything evolves at a very high speed, sometimes it is difficult to keep the focus and not go crazy with the constant changes. In my case, I like to read and practice different programming languages and the more the better, because they bring different visions of how to solve problems and even give you more tools for your day to day. 

And today’s article is about discovering Rust.

Why Rust?

In one of the Lunch & Learns that we do in Apiumhub, a colleague gave me an idea to migrate an internal client that we have in pure bash to some other language and as candidates were Go and Rust, as between us we did not agree, we decided that each would choose a language and make its port.

The result was that that client never migrated, but along the way, both of us were able to discover the advantages and disadvantages of languages like GO and Rust.

From that moment on, I was hooked on Rust and desperate since then, any personal project or proof of concept or idea that I can think of, I try to go first with Rust.

What is Rust?

Rust is based on three pillars:

  • Performance, fast and efficient with memory, no runtime or Garbage collector.
  • Reliability, ownership model guarantees memory-safety and thread-safety.
  • Productivity, great documentation, a compiler that in most cases tells you how to do it and gives you references to the documentation so you understand the problem and a tool that serves as a package manager, code formatter, improvement and suggestions.

Rust began by defining itself as a systems language, but over time that definition has been disappearing, there are more and more libraries for web,  GUI, games and of course for systems!

The first thing that you think when you read “system language” is… I will have to deal with pointers, I will have to work releasing and assigning memory, I will have to work at a very low level without abstractions and of course… if it is not your day to day because it is scary to return to the origins of C C++, but the great majority of these fears are very well resolved and by the compiler! with which it facilitates the way a lot to us.

In this article we will see some basic concepts of rust and some of its features that under my point of view make it a very attractive language.

Rust Concepts

  • Rust has a wide range of primitive types
  • Rust bets on immutability, therefore, all declared variables are immutable unless they are specified with the keyword mut at the time of declaration.
  • The same happens with visibility, everything is private and in the case that you want to make it public you will do it with the keyword pub.
  • In the case of functions we can specify the keyword return to indicate that it is the value to be returned from the function or if the last sentence does not include the ; it will become the return of the function.
  • Rust has a very complete type inference and we rarely need to specify the type of variable we are creating.
  • Other features that give Rust a plus are the Generic types, Pattern matching, Macrosystem and many concepts of functional programming such as first-class functions, closures, Iterators
Rust
 




x
24


 
1
let name = "Jon".to_string(); // String type
2
let year = 2020; // i32 type
3
let age: u8 = 35;
4
 
          
5
let mut index = 0; //mutable variable
6
index = index +=1; 
7
 
          
8
let add_one = |x: i32| x + 1; //closure
9
let two = add_one(1);
10
 
          
11
let numbers = vec![1, 2, 3, 4, 5, 6];
12
let pairs: Vec = numbers.into_iter()
13
        .filter(|n| n % 2 == 0)
14
        .collect(); // [2, 4, 6]
15
 
          
16
fn greet(name: String) {
17
    println!("hello {}", name);
18
}
19
pub fn plus_one(x: i32) -> i32 {
20
    return x + 1; 
21
}
22
pub fn plus_two(x: i32) -> i32 {
23
    x + 2 
24
}


Ownership, Borrowing, & Lifetimes

These three concepts are the greatest complexity that we will find in Rust, since they are concepts that in languages with QA it is the QA itself that treats them making it transparent for the developer.

As it does not have an associated runtime or a Garbage Collector that frees the memory of the objects it does not use, all this is handled by the compiler with the help of the ownership,
Although the concept is suitable for more than one article, let’s see the basics of the concept with some examples.

Each value has an assigned variable (owner) and there can only be one owner at a time, when that owner is out of scope the value will be released.

So we have the following example:

Rust
 




xxxxxxxxxx
1


 
1
fn main() {
2
    let name = "Jon".to_string();
3
    greet(name);
4
    println!("goodbye {}", name); //^^^^ value borrowed here after move
5
}
6
 
          
7
fn greet(name:String) {
8
    println!("hello {}", name);
9
}


The compiler is telling us that the owner of the variable name has been passed to the greet function, so after running greet it is no longer in that scope. To solve it is as simple as indicating that what we want is to lend the owner, so that when the function ends, get the owner again, and that is indicated with &.

Rust
 




xxxxxxxxxx
1


 
1
fn main() {
2
    let name = "Jon".to_string();
3
    greet(&name);
4
    println!("goodbye {}", name);
5
}
6
 
          
7
fn greet(name:&String) {
8
    println!("hello {}", name);
9
}


The lifetime is a check of the management of ownership and borrowing of the values, most of the times the compiler knows how to interpret it, but sometimes it is necessary to detail it. Without going into too much detail since the same as the ownership and borrowing, gives for a series of articles.

Structs

Structs exist to define our own types, they are created with the keyword struct and have no associated behavior.

To give behavior to a struct it will be done with the keyword impl.

Rust
 




xxxxxxxxxx
1
24


 
1
 
          
2
struct Point {
3
    x: f32,
4
    y: f32,
5
}
6
impl Point {
7
    fn add(self, other: Point) -> Point {
8
        Point {
9
            x: self.x + other.x,
10
            y: self.y + other.y,
11
        }
12
    }
13
}
14
let point1 = Point {
15
  x: 10.0,
16
  y: 20.0,
17
};
18
 
          
19
let point2 = Point {
20
  x: 5.0,
21
  y: 1.0,
22
};
23
 
          
24
let point3 = point1.add(point2); //Point { x: 15.0, y: 21.0 }


In the Point implementation the add method receives as parameter self, this is because that method is of instance, if we don’t want to do it of instance it is as simple as removing the self

Traits

The Rust Traits are a collection of methods defined to be implemented by Structs, they are similar to the interfaces of other languages.

Rust
 




xxxxxxxxxx
1
29


 
1
pub trait Summary {
2
    fn summarize(&self) -> String;
3
}
4
 
          
5
pub struct NewsArticle {
6
    pub headline: String,
7
    pub location: String,
8
    pub author: String,
9
    pub content: String,
10
}
11
 
          
12
impl Summary for NewsArticle {
13
    fn summarize(&self) -> String {
14
        format!("{}, by {} ({})", self.headline, self.author, self.location)
15
    }
16
}
17
 
          
18
pub struct Tweet {
19
    pub username: String,
20
    pub content: String,
21
    pub reply: bool,
22
    pub retweet: bool,
23
}
24
 
          
25
impl Summary for Tweet {
26
    fn summarize(&self) -> String {
27
        format!("{}: {}", self.username, self.content)
28
    }
29
}


Enums

We can create enums, without value, with value or even have each enum have values of different types.

Rust
 




xxxxxxxxxx
1
16


 
1
enum IpAddrKind {
2
    V4,
3
    V6,
4
}
5
 
          
6
enum IpAddr {
7
    V4(String),
8
    V6(String),
9
}
10
 
          
11
enum Message {
12
    Quit,
13
    Move { x: i32, y: i32 },
14
    Write(String),
15
    ChangeColor(i32, i32, i32),
16
}


This is where pattern matching and destructuring play a very important role in managing enums

Alias

In Rust, we can create our aliases for existing types.

Rust
 




xxxxxxxxxx
1


 
1
type Second = u64;
2
let seconds: Second = 10;


Adding Functionality to Classes Once They Are Defined

In some programming languages, it is possible to add methods (extension methods) to classes once they have been defined, in Rust this would not be less! First we will create the path with the method that we want to use, then we will implement the path previously created to the type that we want to extend.

Rust
 




xxxxxxxxxx
1
15


1
pub trait Reversible {
2
    fn reverse(&self) -> Self;
3
}
4
 
          
5
impl Reversible for String {
6
    fn reverse(&self) -> Self {
7
        self.chars()
8
            .rev()
9
            .collect::()
10
    }
11
}
12
 
          
13
let hello = String::from("hello");
14
println!("{}",hello.reverse()); // olleh


Operator Overload

Imagine being able to apply arithmetic operations to your own types, following the example before the struct point, being able to add Points with the simple + operator. In Rust this is possible by overloading the operators, which is the same again, implement traits for the types. Here are all the possible operators to overload.

Rust
 




xxxxxxxxxx
1
21


 
1
struct Point {
2
    x: f32,
3
    y: f32,
4
}
5
 
          
6
impl std::ops::Add for Point { // implement Add trait for Point
7
    type Output = Self;
8
 
          
9
    fn add(self, other: Self) -> Self { //implement add function
10
        Point {
11
            x: self.x + other.x,
12
            y: self.y + other.y,
13
        }
14
    }
15
}
16
 
          
17
let point1 = Point { x: 10.0, y: 20.0};
18
 
          
19
let point2 = Point {x: 5.0, y: 1.0};
20
 
          
21
let p = point1 + point2; // apply add trait


Question Mark Operator

It is very common to see the handling of errors in Rust through the type Result<T,E> being T the value of OK and E the one of the error, and the handling of this type is done through pattern matching. Let’s imagine that we want to read the content of a file. For it we will use the function read_to_string of the module fs, the result of this function is a Result<String, std:io::error::Error>.

Rust
 




xxxxxxxxxx
1


 
1
 
          
2
let content = fs::read_to_string("filename");
3
match content {
4
    Ok(file_content) => { println!("{}", file_content) }
5
    Err(e) => { println!("Error reading file: {}", e) }
6
}


By means of pattern matching, we have dealt with both possible cases of the result. For this example, we only wanted to print it by console, but imagine that you want to treat that content, the code becomes a little more complex, for these cases in Rust there is the ? operator with which we directly obtain the value of the Result if it has gone well and if not directly the error will be returned as return of the function. But in order to use the ? operator the method signature has to return a type Result<T,E>

Rust
 




xxxxxxxxxx
1


 
1
 
          
2
fn get_content() ->  Result<String, Error>{
3
    let content = fs::read_to_string("filename")?;
4
    println!("{}", content);
5
    Ok(content)
6
}


If the reading of the file fails, it will automatically return the Error trace, otherwise the code will continue to be executed until it returns the Result ok of the content.

Type Conversion

Another very interesting feature is the type conversion that can be applied in Rust only by implementing the Trait std::convert::From.

The clearest use case is a function where you handle different types of errors but the return of your function you want it to be in the case of error a mistake of yours, of your domain, through pattern matching we could go hunting all the results and creating the Results of our type, but it would make our code difficult to maintain and not very readable.

Using the ? operator and type conversion would look like this:

Rust
 




xxxxxxxxxx
1
26


 
1
fn get_and_save() -> Result<String, DomainError> {
2
    let content:  Result<String,HttpError> = get_from_http()?; 
3
    let result: Result<String,DbError> = save_to_database(content)?; 
4
      // with ? operator in case of error, the return of the function will be Result of Error
5
    Ok(result)
6
}
7
 
          
8
pub struct DomainError {
9
    pub error: String,
10
}
11
 
          
12
impl std::convert::From for DomainError {
13
    fn from(_: DbError) -> Self {
14
        DomainError {
15
            error: (format!("Error connecting with database")),
16
        }
17
    }
18
}
19
 
          
20
impl std::convert::From for DomainError {
21
    fn from(_: HttpError) -> Self {
22
        DomainError {
23
            error: (format!("Error connecting with http service")),
24
        }
25
    }
26
}


Cargo & Utilities

And if we talk about Rust, we can’t leave out your package manager position, which comes with the Rust installation itself.

With cargo we can create a project from scratch, manage the dependencies, generate the release, launch the tests, generate the documentation, publish the package to the registry.

In addition there is a large list of third party commands available.

Resources

Although Rust was created by Mozilla, Rust is maintained by the community, and it is the community itself that proposes the changes and adapts the language to the needs.

Some of the most interesting links to follow in order to keep up with the news:

  • rust-lang.slack: Slack in which all language issues are discussed with a lot of help for those who are new to the language.
  • Weekly: Weekly newsletter with news about language changes, interesting articles and conferences/talks.
  • Youtube: official Rust channel where conferences, meetings of the different working groups formed for language development are posted.
  • Discord: Discord server where most of the working groups are coordinated to maintain the language.
  • The Rust Book: Official documentation about Rust, everything you need to know about the language is in the book.

And a couple of personal projects with which I’m putting into practice everything I’m reading about Rust

  • Adh: is a Docker client, ported from the original ApiumHub with the commands I use most in my daily life, there are still many features to be added.
  • COVID-bot: is a telegram bot developed on Rust to keep track of COVID-19
Topics:
introduction to rust, performance, programming languages, rust, web dev

Published at DZone with permission of Joaquin Caro . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}