Creating a New Package

To start a new package with Cargo, use cargo new:

  1. $ cargo new hello_world --bin

We’re passing —bin because we’re making a binary program: if wewere making a library, we’d pass —lib. This also initializes a new gitrepository by default. If you don't want it to do that, pass —vcs none.

Let’s check out what Cargo has generated for us:

  1. $ cd hello_world
  2. $ tree .
  3. .
  4. ├── Cargo.toml
  5. └── src
  6. └── main.rs
  7. 1 directory, 2 files

Let’s take a closer look at Cargo.toml:

  1. [package]
  2. name = "hello_world"
  3. version = "0.1.0"
  4. authors = ["Your Name <you@example.com>"]
  5. edition = "2018"
  6. [dependencies]

This is called a manifest, and it contains all of the metadata that Cargoneeds to compile your package.

Here’s what’s in src/main.rs:

  1. fn main() {
  2.     println!("Hello, world!");
  3. }

Cargo generated a “hello world” for us. Let’s compile it:

  1. $ cargo build
  2. Compiling hello_world v0.1.0 (file:///path/to/package/hello_world)

And then run it:

  1. $ ./target/debug/hello_world
  2. Hello, world!

We can also use cargo run to compile and then run it, all in one step (Youwon't see the Compiling line if you have not made any changes since you lastcompiled):

  1. $ cargo run
  2. Compiling hello_world v0.1.0 (file:///path/to/package/hello_world)
  3. Running `target/debug/hello_world`
  4. Hello, world!

You’ll now notice a new file, Cargo.lock. It contains information about ourdependencies. Since we don’t have any yet, it’s not very interesting.

Once you’re ready for release, you can use cargo build —release to compileyour files with optimizations turned on:

  1. $ cargo build --release
  2. Compiling hello_world v0.1.0 (file:///path/to/package/hello_world)

cargo build —release puts the resulting binary in target/release instead oftarget/debug.

Compiling in debug mode is the default for development— compilation time isshorter since the compiler doesn't do optimizations, but the code will runslower. Release mode takes longer to compile, but the code will run faster.