Hello World

In the time-worn tradition, our first Rust program will be getting our computer to greet this wide world of ours.

Let's start by making a directory to work out of1:

$ cd ~
$ mkdir yarr
$ cd yarr

For the rest of this course, we'll assume that you're in the ~/yarr directory.

Now let's make our first Rust program. When we installed rustup and the Rust toolchain, it included a tool called cargo. This is the Swiss army knife for Rust. It takes care of a lot of things for you, including:

  • Installing and updating packages
  • Creating new projects
  • Running your tests
  • Executing your binary
  • Formatting and linting your code
  • Publishing your library

We'll learn by doing, but feel free to explore the other functions with cargo help or in the Cargo docs.

To create a new project, you can use cargo new:

$ cargo new hello_world
Created binary (application) `hello_world` package

If you print out the directory that was created, there are a few files:

├── Cargo.toml
└── src
    └── main.rs

Now we can run the program:

$ cd hello_world
$ cargo run
   Compiling hello_world v0.1.0 (/home/ntietz/Code/ntietz/rust-crash-course/hello_world)
    Finished dev [unoptimized + debuginfo] target(s) in 0.55s
     Running `target/debug/hello_world`
Hello, world!

And we printed it out!

Whoops, we cheated our way to "hello world" without actually writing the program! But we know our toolchain works. Let's delete the existing file and write our own:

$ rm src/main.rs

Now open src/main.rs as a new file in your editor of choice, and write this program:

fn main() {
    println!("Ahoy, matey!");

Now when you run it, you should see our new, corrected, greeting:

$ cargo run
   Compiling hello_world v0.1.0 (/home/ntietz/Code/ntietz/rust-crash-course/hello_world)
    Finished dev [unoptimized + debuginfo] target(s) in 0.27s
     Running `target/debug/hello_world`
Ahoy, matey!

A few quick notes on the program we wrote, then we'll move on:

  • This declares the main function, which has no return value here but can have a return value in some cases; we'll cover that later in Error Handling.
  • It does only one thing, which is invoking println!. This looks like a function, but is a macro. Macros always end in !, so when you see that you know it's a macro. You can think of macros as fancy powerful functions, and use them just like you would use a function. We won't write our own in this course.


  1. Repeat the hello world program from scratch in a new directory, going by memory as much as possible.
  2. Find and read the documentation on println!. What do you find surprising? What do you find normal?

And now we're ready to move on! Stretch, shake it out, and then move on to learn about variables, functions, and control flow!


If you prefer a different working directory, feel free to do as you wish!