Rust in less than a coffee break

0xksure
6 min readMay 4, 2021
Photo by Jørgen Håland on Unsplash

First, congratulations on starting your journey towards becoming a Rustacean! Rust is a static programming language that can guarantee memory safety thanks to the borrow checker. It has experienced increasing popularity over the last couple of years and has started to be adopted by companies like Microsoft and Facebook.

The language is often compared to golang and cpp as the syntax is similar to the former and the performance is not far of the latter. Steep learning curve often comes up in the context of learning rust. I started looking into the language about 6 months ago and I cannot lie the learning curve has been steep alright. There are a lot of terms and syntax that you find in few languages such as macros, borrow checker and lifetimes. However as I studied the Rust book diligently and started hammering away on small programs I finally got the hang of it.

And now it is your turn 🎉

Optimized developer experience

Before starting developing your new memory safe open source project we need to settle on an optimal developer experience. First, we need to install rustup. For mac and linux distros it’s enough to use curl and execute the script like this in your terminal

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Rustup comes with the build and package management tool cargo which makes it very easy to start developing. Try running

rustup --version

if you get command not found then try restarting the terminal. If this works then great you are ready to develop with rust 🎉

If you are like me and have commited to vscode then I recommend the rust-analyzer extension. This gives you code and syntax highlighting, code completion, go to definition and much more.

Now we are ready to start out project. In your favorite project folder type

cargo new my-first-rust-app

Now move into your newly created rust app by typing

cd my-first-rust-app

And finally let’s put cargo to work by typing something as simple as

cargo run

This command will automatically compile your project starting from the main.rs file and then execute the binary. This should return nothing else then

Hello, World! 

Crates

This is in practise the same as modules in go, packages in python and libraries in cpp etc. The choice of name is probably related to the name of the package manager, cargo. The package management is similar to npm if you have ever used node.js. You have a Cargo.toml file in your project root where the dependencies, external and internal, are listed. Yes, you can create your own crates within your project as your project grows. But that’s a different post for a later time.

To find interesting and useful crates visit crates.io. Here you can find information regarding different crates with examples, current versions and link to the github project and official documentation.

If you find an interesting crate then copy the crate in the format

crate = "x.x.x"

so for the crate rand that is

rand = "0.8.3"

then head over to your Create.toml and paste the line right under dependencies. How you do it is also documented in the crates.io page.

Now run

cargo update

to update the dependencies although the cargo run command that we used earlier will also do this.

To use the newly installed crate head over to you .rs file. For the newly created project that would be the main.rs file. If you want to generate a random number this can then be done as

Pretty cool right? 🙌

Show me an example

As a web developer it would be cool to create a simple webserver that exposes an endpoint. I will brush over the lower level concepts such as concurrency and just let the a crate handle it for us.

I am personally fan of the rocket 🚀framework and it seems like that’s the norm among most rust web developers. It is very intuitive and easy to get started with. Just check out their blazing website

Gotcha: One important point made in both the documentation and on their website is that Rocket uses the nightly version of rust. In order to enable this feature run

rustup override set nightly

in the root of your project. Rumors have it that Rocket version “0.5.0” will use the stable version of rust. When that happens is beyond my knowledge.

Cool, let’s move on. So we have seen how easy it is to add new crates in rust. Let’s just grab the latest version of Rocket and add it to our Cargo.toml file.

Time to create our GET endpoint /rand that returns a random number to the client when requested. To make it simple we will only return a string like

{“random_number”:"42"} 

First we need to create our function random_number which will look like this

So the syntax is basically fn <function_name> -> type{…}. In this case we return a String. On line 2 we generate the random number as an 8-bit unsigned (positive number) integer type and converts it to a string by using the method to_string(). Finally the format!() function is used to create the json String.

As you can see there is no return statement. This is because the last line not ending with a semicolon (;) in a function is considered the return statement. It is of course possible to explicitly write

return format!("{{ 'random_number': {}' }}", random_number);

Also notice the way format is used. The second and higher arguments are inserted into the first String argument where the expression {} is. This means that

>format!("{}{}{}", "Hello", ",", " World")
> Hello, World

Moving along, we will need to put this function in the context of Rocket. In our case that is making sure this function in called on GET /random. This can be achieved by something called a macro. I will not go into this right now but you can read more about it in the Rust book. In our case we will use the GET macro 😆 like this

On line 7 you can see the macro in action. We expect to call the random_number function on GET /random and return a String. As you notice Rocket does a lot behind the scenes. On line 14 we have defined the main() function which is the entrypoint of our app. While on line 15 we ignite (because, you know, rocket) and mount in this case one route starting on / and then we launch out rocket. Finally we are ready for takeoff 🚀

Head over to your terminal at the root of your project (where the Cargo.toml lives) and run cargo run. You should now see a bunch of information regarding the setup of similar to

Type localhost:8000/random in your browser of choice and watch how your screen lights up with the json.

Congratulations you have successfully created a webserver in Rust 👏

The full project can be found on github

Conclusion

As you probably noticed there were a lot of features in Rust that I did not dive deep into. This included things like lifetimes, the borrow checker, macros, concurrency and much more. However we got a nice webserver set up on nightly Rust in about no time.

Please follow me on twitter for anything Rust, Javascript, Golang and Blockchain related https://twitter.com/kristohberg

Resources

If you want to continue to learn more about Rust I would highly recommend

--

--