At MagmaLabs we always keep up to date by trying and using new technologies because of our client’s requirements. But, we also keep on trends to feed our curiosity, and learning about Rust couldn’t be the exception. Want to know more about this low-level statically-typed multi-paradigm programming language focused on performance and security? Well, keep reading.
A brief intro to Rust
Rust is not only one of the most loved languages in recent years, it is also a robust and memory safe language. Oh, and its use in top companies has increased notably!
Aside from Ruby and JavaScript, Rust is a compiled language, which means that we have to build our program before using it (just like Java or C++).
Another big difference is that Rust is hardly typed, so we have to declare the type of our variables and the parameters that receive and return our functions. Certainly, this is necessary since the compiler needs to know how much memory it has to assign to a variable at compilation.
How to install Rust
Obviously, like every language or tool, we need to install it first.
Lucky for you, Rust community has already automated all the process. You can find more details on Rust’s install page, but you only need to run this line in your terminal:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
This script installs Rust Compiler, Cargo, and other Rust utilities.
You can also try Rust in your browser without installing anything with Rust Playground
Hello world
Let’s start with a typical hello world:
// hello.rs
fn main() {
println!("Hello, MagmaLabs! 🦀");
}
As mentioned, we need to compile our program before using it.
How? We do that with the Rust Compiler (rustc
):
$ rustc hello.rs && ./hello
Hello, MagmaLabs! 🦀
Now, let’s analyze our hello program.
We use fn
to define functions in Rust.
We have a main
function. All rust programs need a main function, this is where we define what our program will execute when we run our binary.
Each line ends with a ;
(so Js)
We use println!
for print in the console. Something interesting here is the !
at the end. This is because println!
is a Macro.
We do not convert Macros in this post; but it is important to know that Macros are a way to extend the language, writing code that writes other code.
Play with syntax
Well, now let’s play a bit with Rust syntax.
// syntax.rs
fn sum(a: i32, b: i32) -> i32 {
a + b
}
fn main() {
let x: i32 = 10;
let y: i32 = 5;
println!("sum is: {}", sum(x, y));
}
Compile and run
$ rustc syntax.rs && ./syntax
sum is 15
We have a main function where we declare two variables using the let
keyword, similar to JavaScript. There, we are defining the type of the variable. In this case, it is not necessary to define the type of the variable since the compiler can infer, but it is a good idea to get that mindset to always declare our types.
Aside from the main
function, we have a sum
function that receives two parameters and returns the sum of both. Wi this we are declaring the types that receive and return our function.
You can notice that we do not have a semicolon (‘;’) here. So, we do not end a statement with a semicolon. If we do so, that means we are indicating to return the value of this line.
The compiler is your friend
We have this snippet which is similar to our hello.rs
// compiler.rs
fn main() {
let s0 = String::from("hello");
let s1 = s0;
println!("{}, Magma!", s0);
}
Let’s compile …
$ rustc compiler.rs && ./compiler
warning: unused variable: `s1`
--> compiler0.rs:3:9
|
3 | let s1 = s0;
| ^^ help: if this is intentional, prefix it with an underscore: `_s1`
|
= note: `#[warn(unused_variables)]` on by default
error[E0382]: borrow of moved value: `s0`
--> compiler0.rs:5:28
|
2 | let s0 = String::from("hello");
| -- move occurs because `s0` has type `String`, which does not implement the `Copy` trait
3 | let s1 = s0;
| -- value moved here
4 |
5 | println!("{}, Magma!", s0);
| ^^ value borrowed here after move
error: aborting due to previous error; 1 warning emitted
For more information about this error, try `rustc --explain E0382`.
Boom! .. The compiler told us that there is an error and a warning in our code.
Our error is that we are trying to reference a variable that was moved. In Rust we have the concept of ownership, which means it can only be one owner for each value.
We can solve the problem by cloning the variable.
The warning is something that does not prevent the compilation, but it is a hint to improve your code.
So, we update our program to:
fn main() {
let s0 = String::from("hello");
let _s1 = s0.clone();
println!("{}, Magma!", s0);
}
Compile and ..
$ rustc compiler1.rs && ./compiler1
hello, Magma!
Everything works! 😀
Using external packages
Packages in Rust are called Crates. Do you remember that we mentioned that the rustup script installed Cargo? well, Cargo is the dependency manager in Rust. Think of this as a Bundler for Ruby.
Generate a new crate:
cargo new my-crate
Next open Cargo.toml
(a kind of gemspec) and add some dependencies
[dependencies]
magma-says = "0.1"
Write this code in your main.rs
use magma_says;
fn main() {
let out = "Hello Rustaceans!";
magma_says::say(out);
}
Now execute your program.
cargo run
You can get something like:
-----------------
Hello Rustaceans!
-----------------
\
\
..................................
................................
..........###..................
........#####.................
......(###,.................
.......#...................
//...........((............
////........,((((...........
/////// .....((((((,..........
////// ...((((((............
*////// ((((((/.............
////// ((((((......####.....
.////// (((((((......######....
//////, ...(((.........#######..
////// .....(............######.
...........................
#WeAreMAGMA
What’s next?
Hope this post encourages you to learn more about Rust. You can continue learning about it with:
- Read the Rust Book
- Check Rust by example
- Do Rustlings exercises
- Join Rust Discord and find local Rust communities near to you
Conclusion
At first, Rust could seem a little bit tough if you are not familiar with compiled languages, but after some practice, you will love how the compiler helps you write more efficient code.
Let’s give Rust a try and tell us about the amazing things you build with it.
If you have doubts about Rust, how to install it, or want to continue talking about it, please write me in the comments!!
Thanks for reading!