Rust, lesson 1
Every Rust program starts running at a function called main. The compiler turns your file
into a program, and when you run it, main executes its statements from top to bottom.
A few things to notice:
fn declares a function. main takes no arguments here.{ and }.;.println! has an exclamation mark because it is a macro, not a normal function. Macros
are code that writes code; println! checks your format string while compiling, so a typo
in it is caught before the program ever runs.2 exercises to try what you just read.
println! prints a line and ends it with a newline. print! does the same without the
newline. Both take a format string in which each {} is a placeholder filled by the
next argument:
You can also write a variable's name directly inside the braces, which keeps long format strings readable:
To print an actual brace, double it: {{ and }}. Escape sequences such as \n (new line)
and \t (tab) work inside strings, and \" prints a quote.
Inside the braces, after a colon, you can control the format:
// starts a comment that runs to the end of the line. /* ... */ can span several lines.
Comments starting with /// are documentation comments, used to describe the item below
them; tools turn them into web pages.
Rust is compiled ahead of time. The compiler, rustc, reads your whole program, checks types
and memory safety, and only produces a runnable program if everything is correct. When
something is wrong it prints an error with the line number and often a suggested fix.
Read those messages carefully; the Rust compiler is famous for helpful ones.
The compiler also gives warnings, for example about a variable you never use. Warnings do not stop the program from running, but they usually point at something worth cleaning up.
Write a program that prints exactly these two lines:
The program reads no input.
Print this small price list using println! with format options. Each item name is
left-aligned in a column 8 characters wide, and each price has exactly two decimals and is
right-aligned in a column 6 characters wide. The values are "tea" with 2.5, "cake" with
3.75 and "scone" with 12.0.
The program reads no input.
fn main() {
println!("Hello, World!");
println!("Rust runs main from top to bottom.");
}println!("Score: {}", 42); // Score: 42
println!("{} has {} lives", "Kit", 3); // Kit has 3 lives
print!("Loading");
print!("...");
println!("done"); // Loading...donelet player = "Kit";
println!("Welcome back, {player}!");println!("{:.2}", 3.14159); // 3.14 (two decimals)
println!("[{:>5}]", 42); // [ 42] (right-align in 5 columns)
println!("[{:<5}]", "ab"); // [ab ] (left-align)
println!("{:03}", 7); // 007 (pad with zeros)// This explains the next line.
println!("This runs"); // a comment after code
/* A longer note
across lines. */Hello, World!
I am learning Rust.tea 2.50
cake 3.75
scone 12.00