Rust Programming Language Learning Note - Part 1

Rust is a modern compiled programming language. It is fast and secure, it is a strong-typed language, and it can build any type of program. Due to tiny binary output, it is suitable to build tiny docker images for running on the cloud.

I want to learn it because I want to replace some JS programs running on my private cloud with Rust programs. JS runtime is heavy, and not type-safe and memory-safe, the docker images are also heavy (with dependencies\ up to 500MB). The rust programming language seems to solve all of my pains, so let me try it.

The learning material I used is the Rust Course which is written in Chinese. For English readers, I recommend the official book The Book. All codes run on a 2020 M1 Mac Mini (16+512) under macOS Monterey (12.4).

Setup Rust

On macOS, setting up the environment for rust programming is very simple with brew. Just search for rustup, install it with

1
2
$ brew install rustup-init
$ rustup-init

and follow the prompts to finish the installation. It will install all rust toolchains including the compiler rustc and the package and project manager cargo. A C-compiler is possibly also necessary, install it with

1
$ xcode-select --install

As always, Hello World

It is extremely simple to create a Hello World program for rust:

1
$ cargo new world_hello

and you will have a folder named world_hello with an already well-written “Hello World” rust program. Just run it with

1
$ cargo run

and you will see the following outputs

1
2
3
4
  Compiling world_hello v0.1.0 (/***/world_hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.42s
Running `target/debug/world_hello`
Hello, world!

and boom, a rust version “Hello World” is finished, fast and simple.

But you may notice the debug in the path, which indicates that the compiling target is a debug version of program. To obtain a release version, just append --release to cargo run command:

1
2
3
4
5
$ cargo run --release
Compiling world_hello v0.1.0 (/***/world_hello)
Finished release [optimized] target(s) in 0.42s
Running `target/release/world_hello`
Hello, world!

Another great thing is that cargo new will also initialize the folder as a git repository, and add a default .gitignore for you, which is very convenient.

All information about this “Hello World” program is recorded in Cargo.toml file:

1
2
3
4
[package]
name = "world_hello"
version = "0.1.0"
edition = "2021"

The edition field indicates that this rust program will use the 2021 edition to compile. The rust release edition every 3 years, the last two editions are 2015 and 2018. 2021 is therefore the latest edition.

Summary

What I learned from this part:

  1. How to set up the Rust development environment
  2. How to create a new rust project
  3. How to run a rust project
  4. How to determine rust project information

Next, I will learn deeper the syntax and features of the rust programming language.