Analyzing Functional in Rust
Any personal project or proof of concept or idea that I can think of, I try to go first with Rust.
Join the DZone community and get the full member experience.Join For Free
Being a developer, it is easy to jump on the hype train and 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, in Apiumhub, we 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.
In one of the lunch and learn 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 Garbaje collector.
- The reliable ownership model guarantees memory-safety and thread-safety.
- Productive, 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.
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.
This article will see some basic rust and some of the features that make it a desirable language. under my point of view
- 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 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, Macro system, and many functional programming concepts such as first-class functions, closures, and Iterators.
Ownership, Borrowing, and Lifetimes
These three concepts are the greatest complexity that we will find in Rust since they are concepts that in languages with QA, the QA itself 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:
The compiler tells us that the variable name's owner 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 and
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 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.
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, it is as simple as removing the self.
The Rust Traits are a collection of methods defined to be implemented by Structs, they are similar to the interfaces of other languages.
We can create enums, without value, with value or even have each enum have values of different types.
This is where pattern matching and destructuring play a vital role in managing enums.
In Rust, we can create our aliases for existing types.
type Second = u64;
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 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.
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
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>.
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? The operator with which we directly obtain the vResult's value if it has gone well and if not directly, the error will be returned as return of the function. But to use the? operator the method signature has to return a type Result<T,E>
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.
Another exciting 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. Still, the return of your function you want it to be in the case of an 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:
Cargo and 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…
Also, there is a large list of third party commands available.
Although RMozilla created rust is maintained by the community, it is the community itself that proposes the changes and adapts the language to the needs.
Some of the most interesting links to follow 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.
Covid-bot: is a telegram bot developed on rust to keep track of covid-19
Published at DZone with permission of Joaquin Caro. See the original article here.
Opinions expressed by DZone contributors are their own.