2  Hello, World!

Objective

Learn how to create a new Rust crate and understand its file structure. You will know how to use cargo run and the println!() macro.

Rust uses a tool called cargo for building, checking, and managing dependencies. This is installed for you when you used rustup to install Rust.

To create a new Rust crate, use cargo new name-of-crate. This creates a new directory called name-of-crate. Be sure to cd into that directory.

cd is short for change directory. We use this to…yup…change the directory from the terminal.

Crate anatomy

Two types of crates: binary, library.

This first workshop we will work only with a binary crate. We will create a library in the second half of the day.

Binary crates are standalone applications like command line tools, or things that run once—simiar to a script that you run with Rscript main.R

Crate anatomy

A new crate looks like this:

intro-to-rust/
├── Cargo.toml      # Metadata & dependencies (like DESCRIPTION)
├── Cargo.lock      # Dependency versions (like renv.lock)
└── src/
    └── main.rs     # Entry point — like main.R

main.rs

When you create a new rust binary the file src/main.rs is prepopulated with:

src/main.rs

The main() function defines what is executed when your binary is run.

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

There are a few things going on in here:

  • Functions are declared using the fn keyword
  • The main() function is the entrypoint of the program (and required)
  • Blocks of code are delimted using curly braces (like R & C)
  • Statements end with ;
  • println!() is a macro (notice the !) which is used to print to stdout

When a program writes to the console it does so through file connections called standard output (stdout) and standard error (stderr).

When we print a message with print() or message() in R, we print to stdout. When we make a warning or error using stop() or warning() in R, that is writing to stderr.

Variables can only be defined inside of the main() function.

println!()

  • Macros have a !, like println!().
  • Think of it like print() in R, but explicit.
  • It supports format strings:

Using placeholder

let name = "Josiah";
println!("Hello, {}!", name);

Direct interpolation

let name = "Josiah";
println!("Hello, {name}!");

Exercise

  • In your terminal, create a new rust crate called intro-to-rust
  • Open the new Rust crate’s folder in Positron
  • Run the hello world program using cargo run
  • Create a variable called name inside of the main() function with your name
  • Print Hello, {name}! using println!()
  • To run it navigate to your terminal and then enter cargo run.

Solution

View solution

In src/main.rs

fn main() {
    let name = "Josiah";
    println!("Hello, {name}!");
}