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, printHello, 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 Ruston 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 out6 * 7.Print
10 apples and 5 pears, with two{}and the numbers10and5after 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
mainthat 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
HELLOon the first line.Print
my name ison the next line, then any name on the line after.On the last line, use
{}to printBadge number 7, with the 7 worked out from3 + 4.
More in Rust Basics
Previous: STL Algorithms and Lambdas · Next: Variables