Hello, World!

Programming Languages · Rust Basics · 8 min

Write your first Rust program: print text, fill in values with {} and leave notes for humans.

Your first Rust program

Every Rust program starts in fn main(). The code between its { and } runs when you press Run.

println! prints a line of text. The ! means it's a macro, a special kind of command. For now, just remember the !. Each line ends with a ;.

fn main() {
    println!("Hi there");
}
  • Inside main, print Hello, World!

One println!, one line

Each println! prints its own line. Rust runs your lines from top to bottom, in order, like a recipe.

println!("Step 1");
println!("Step 2");
  • Print I am learning Rust on the first line.

  • On the next line, print It is fun.

The {} placeholder

To print a value, put {} in the text and the value after a comma. Rust swaps the {} for the value:

println!("I have {} cats", 2 + 1);

That prints I have 3 cats. With two {}, the values fill them in order.

  • Print The answer is 42, using {} and letting Rust work out 6 * 7.

  • Print 10 apples and 5 pears, with two {} and the numbers 10 and 5 after the text.

Comments are notes for humans

A line that starts with // is a comment. Rust skips it completely. Programmers use comments to explain why the code does something.

// This line is ignored
println!("This one runs");
  • Add a comment inside main that says what the program does.

  • Below it, print Comments are skipped.

Put it together: a name badge

Time to combine everything. Make a little name badge that prints four lines. You can use your own name.

  • Print HELLO on the first line.

  • Print my name is on the next line, then any name on the line after.

  • On the last line, use {} to print Badge number 7, with the 7 worked out from 3 + 4.

More in Rust Basics

Previous: STL Algorithms and Lambdas · Next: Variables