| title | slug |
|---|---|
Hello World |
hello-world |
fn main() {
println!("Hello, world!");
}fn means function. The main function is the beginning of every Rust program.
println!() prints text to the console and its ! indicates that it’s a macro rather than a function.
💡 Rust files should have
.rsfile extension and if you’re using more than one word for the file name, follow the snake_case convention.
- Save the above code in
file.rs, but it can be any name with.rsextension. - Compile it with
rustc file.rs - Execute it with
./fileon Linux and Mac orfile.exeon Windows
Rust Playground is a web interface for running Rust code.
-
These are the other usages of the
println!()macro,println!("{}, {}!", "Hello", "world"); // Hello, world! println!("{0}, {1}!", "Hello", "world"); // Hello, world! println!("{a}, {b}!", a = "Hello", b = "world"); // Hello, world! let (a, b) = ("Hello", "world"); // 💡 Two Variable bindings declare & initialize in one line. println!("{a}, {b}!"); // Hello, world! println!(); // A new line
// Debug print and pretty-print debug print format specifiers println!("{:?}", [1, 2, 3]); // [1, 2, 3] println!("{:#?}", [1, 2, 3]); /* [ 1, 2, 3 ] */ // 💡 We can use the variable directly with the format specifier as well. let a = [1, 2, 3]; println!("{a:?}"); // similar to println!("{:?}", a); println!("{a:#?}"); // similar to println!("{:#?}", a);
-
Rust has a
print!()macro as well.print!("Hello, world!\n"); // With new line print!("Hello, world!"); // Without new line
-
The
format!()macro is used to store the formatted string.let a = format!("{}, {}!", "Hello", "world"); println!("{a}"); // Hello, world!
-
Let's play a bit more...
println!("{}", "Hello, world!".to_uppercase()); // HELLO, WORLD! println!("{}", "Hello, world!".to_lowercase()); // hello, world! println!("{}", "⭐️".repeat(3)); // ⭐️⭐️⭐️ println!("{}", "Hello, world!".chars().count()); // 13 // 💡 For more accurate results, you should use a crate like unicode_segmentation that follows more accurate Unicode text segmentation standards.
-
Different format specifiers.
let a = 255; println!("{a}"); // 255 println!("{a:b}"); // Binary 💡 11111111 println!("{a:o}"); // Octal 💡 377 println!("{a:x}"); // LowerHex 💡 ff println!("{a:X}"); // UpperHex 💡 FF println!("{a:0>5}"); // Add leading zeros till character lengh 5 💡 00255 println!("{a:0<5}"); // Add tailing zeros till character lengh 5 💡 25500
-
Check the difference between macros and functions.
-
For more
rustccommands, check therustc --helpcommand.
