[Avg. reading time: 4 minutes]
The Basic Program
- Rust code is always put in a file with
.rsextension. - Every executable Rust program starts execution from the main function.
fn main() { println!("Hello World!"); }
println! prints text to standard output and automatically adds a newline at the end.
- println! is a macro not a function.
- Macros are evaluated at compile time.
Example 2:
Rust does not use string interpolation like Python or JavaScript. Instead, it uses format placeholders inside the string.
fn main() { println!("Number: {}", 1); }
{} is a placeholder.
Printing variables
fn main() { let age = 25; println!("Age: {}", age); }
Positional Arguments
Arguments are filled in same order.
fn main() { println!("{} last name is {}", "Rachel", "Green"); }
Named Arguments
Helps in code readability.
fn main() { println!("{fname} last name is {lname}", fname="Rachel", lname="Green"); }
This is different from string interpolation in python.
Using Expressions
fn main() { println!("{} * {} = {}", 15, 15, 15 * 15); }
Number Formatting
Rust supports multiple number representations using format specifiers
fn main() { println!( "Decimal: {}\nBinary: {:b}\nHex: {:x}\nOctal: {:o}", 20, 20, 20, 20 ); }
Debug Printing {:?}
fn main() { println!("{:?}", (100, "Rachel Green")); }
fn main() { println!("{}{:?}", "Rachel Green", "Rachel Green")); }
Debug printing it for debugging, not for user facing outputs.
We will discuss about Debug Trait in later weeks.