Learn how to create a Rust project using Cargo.

WHat is Cargo?

Cargo is a build system and package manager for Rust. It helps developers download and manage dependencies and assists in creating Rust packages, otherwise known as crates.

In this article you will learn how to start using cargo in simple projects. For example to create, build and run a Rust project.

Example 1: First Cargo Project

Upto now we've not been creating and running our Rust projects by hand without Cargo. Cargo can streamline this process and generate us project template, as well as allowing build and run easily using simple commands.

Step 1: Create Project

The first step is to create a Rust project . Here's how you do that using Cargo:

cargo new _02_hello_cargo

The above statement will create a Cargo.toml file. Here's an example of it's contents:

[package]
name = "hello-cargo"                    # what's the name of this package?
version = "0.1.0"                       # what's the version of this package?
authors = ["John Doe <[email protected]>"]  # who wrote this package?
edition = "2018"                        # rust edition
# see: https://doc.rust-lang.org/edition-guide/editions/index.html

# this package doesn't depend on other packages (crates),
# so this is empty.
[dependencies]

Inside the created project there will be an src folder with our main.rs file.

Step 2: Dependencies

No dependencies are needed for this project.

Step 3: Write Code

Then a simple Hello World project:

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

Run

Save the code and run your code as follows using Cargo:

$ cargo run

If you want to build without running then use cargo build:

$ cargo build