Get started with Rust. After building hello world let's build a server. Discover the hidden qualities of this growing language

Get started with Rust. After building hello world let's build a server. Discover the hidden qualities of this growing language

Get started with Rust. After building hello world let's build a server. Discover the hidden qualities of this growing language
Rust programming language logo

The Rust programming language has consistently been most loved by developers worldwide. It has a unique mix of type safety, memory safety, and concurrency.

Similar to C and C++, Rust does not ship with a runtime for resource management. Rust is compiled language; and has performance that is on par with C/C++. This is one of the reasons why it is popular for systems programming.

In this article I will describe how I've setup my environment create a simple program to illustrate how you can get started with Rust.

Development Environment

For my operating system I use Fedora Linux. But don't worry if you're on Windows you can also have a similar setup with WSL. By using Linux within Windows you will have a much better development experience. You can skip this step if you're already on Linux on Mac.

If your chosen distribution doesn't not package all the Rust tools mentioned here, than you can rustup to download and install all of them. Otherwise, use your package manager to install the following packages.

sudo dnf install rust cargo rust-analyzer rust-src rustfmt
shell command to install Rust development tools

I would also like to mention here that I'm using Toolbx for development environment. This is a great tool if you want to create multiple different development environments. I've also written in the past about seamlessly using a Toolbx container with VS Code for development with all the development features available to natively installed packages. This creates a really flexible setup, I highly recommend it. If you're using Windows, you can even use WSL as the environment for VS Code in Windows.

Finally, make sure you have the Rust extension pack installed on your VS Code.

Hello, World

Because it's tradition

As with every new language, let's start by writing a simple Hello World program. This step is mainly for getting familiar with the project creation, compilation, and execution methods.

So run the following in a terminal or command prompt:

cargo new hello_world

Open that new folder in VS Code and you'll see that you already have a src/main.rs file that prints out Hello, world!. It should look like this:

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

Now all this is doing is creating a main function and using println! macro to print a string out to the terminal. Let's run the project:

cd hello_world
cargo run

You should see the following output:

Compiling hellow_world v0.1.0 (/home/mbaig/Projects/personal/rust/hellow_world)
Finished dev [unoptimized + debuginfo] target(s) in 0.13s
	Running `target/debug/hellow_world`
Hello, world!

That's it. We successfully printed out "Hello, world." Now let's make something a little more complex.

Web server

Because everything talks HTTP

If we want to make a web server out of our Rust project we need to first download a couple of packages. Open up the Cargo.toml file and add the following lines to the dependencies section:

actix-web = "4.2.1"
serde = { version = "1.0.145", features = ["derive"] }

These packages, crates in Rust lingo, provide an easy interface for creating a web server. actix-web provides some nice middleware features as well, similar to the ExpressJS framework for NodeJS.

Now let's modify main.rs to create web server.

mod base;

use actix_web::{App, HttpServer};
use base::greet;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(greet)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

The main function here creates our main HTTP server. This server runs on localhost port 8080. We need to use await at the end here because the run method returns a Future and we need to evaluate it.

We also have a custom module called base that provides us with our functionality. Let's create a base.rs file next to the main.rs file. The file tree should look like this:

.
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── base.rs
│   └── main.rs

Now let's populate the file with the necessary code to make everything work:

use actix_web::{get, web, Responder};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct MyObj {
    hello: String
}

#[get("/")]
async fn greet() -> impl Responder {
    web::Json(MyObj {
        hello: "world".to_lowercase()
    })
}

Here we are implementing an actix_web responder. This responder is going to handle the root path. In this module we are creating a struct that will be the basis for our JSON response.

Now we can run our server using the following command:

cargo run

This command will take some time initially because Rust will compile everything and run the project. If all goes well you should have a running server and if you visit http://127.0.0.1:8080/, you should see the following JSON response:

{"hello":"world"}

You can find the code for this in the following repo.

In the future I will be expanding on this project to with multiple other features like processing CSS, and templating.

💻
Happy hacking!