CodeBlanks Logo Icon CodeBlanks

Project with Cargo

Learn to set up a project with cargo new, Cargo.toml and the target folder.

Projects with Cargo

Cargo is Rust's build tool and package manager. It creates new projects, downloads dependencies, builds, runs and tests:

cargo new merhaba     # new project
cd merhaba
cargo run             # build and run
cargo build --release # optimized build
cargo test            # run tests

cargo new creates a Cargo.toml file and src/main.rs.

Cargo.toml

Cargo.toml holds the project's identity and dependencies:

[package]
name = "merhaba"
version = "0.1.0"
edition = "2021"

[dependencies]
rand = "0.8"

The exact versions of dependencies are written to Cargo.lock, so the same versions are used on every machine. Packages are downloaded from crates.io.

Practice Package info

Cargo provides the package name and version as environment variables during the build. Try it with fixed values instead of env!("CARGO_PKG_NAME"): declare let ad = "merhaba"; let surum = "0.1.0"; and print println!("{} v{}", ad, surum);.

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn main() {
    let ad = "merhaba";
    let surum = "0.1.0";
    println!("{} v{}", ad, surum);
}

Expected output

merhaba v0.1.0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What is the difference between <code>cargo build --release</code> and <code>cargo build</code>?

  • --release optimizes; output goes under target/release Correct answer
  • --release runs the tests
  • There is no difference
  • --release publishes the code

Explanation: The default build compiles fast but runs slowly (target/debug); --release compiles slowly but runs much faster.

2 Run

Question
cargo ____   # builds and runs
Answer
cargo run   # builds and runs

Explanation: cargo run builds the project and runs the binary right away.

3 Command and role

Term Meaning
cargo new Creates a project
cargo run Builds and runs
cargo test Runs the tests
Cargo.lock Exact versions

All lessons in Beginner