Skip to main content

Chapter1 Getting started

In this chapter, we'll discuss:

  • Installing Rust on Linux, macOS and Windows
  • Writing a program that prints Hello, World!
  • Using cargo, Rust's package manager and build system

Create a HelloWorld Project

Firstly, install Rust by using the command line tool: rustup.

Now we can create a "Hello world" app:

  1. Creating a project directory

  2. writing and running a Rust program

    fn main() {
    println!("Hello world");
    }
  3. Compiling and running are separated steps.

    Before running a Rust program, you must compile it using the Rust compiler by entering the rustc command and passing it the name of your source file: rustc main.rs.

    Rust is an ahead-of-time compiled language.

Next, we'll introduce the Cargo tool, which will help you write real-world Rust porgrams.

  1. Cargo is Rust's build system and package manager. You can use it to:

    • Building your code
    • Downloading the libraries your code depends on
    • Building those dependencies
  2. Create a project with Cargo:

    cargo new hello_cargo
    cd hello_cargo

    It creates the following files/folders for us:

    • main.rs file

    • Cargo.toml file

    • .git folder

    • src folder

    • .gitignore file

    You may use different VCS other than GIT by specifying the --vcs flag.

  3. Inside the Cargo.toml file is the configuration for our project:

    • [pakcage]: is a section heading that indicates that the following statements are configuring a pacakge.
    • [dependencies]: is a the start of a section for you to list any of the project's dependencies.(In Rust, packages of code are referred to as crates)
  4. Rust expects all the source files to live inside the src folder. Using Cargo helps you to organize your projects.

Building and Running a Cargo Project

  1. Build your project with:

    cargo build
  2. Run the executable with:

    ./<executable-name>
  3. But we can compile the code and then run the resulting executable all in one command:

    cargo run

    The resulting executable can be found inside the target/debug directory.

  4. If you are continually checking your work while writing the code, using cargo check will speed up the process.

  5. When ready for release, you can use cargo build --release to compile your proejct with optimizations. This will create an executable in target/release directory.