Printing to Console
Part of the Fundamentals section of Coddy's Rust journey — lesson 29 of 75.
In Rust, you can print output to the console using the print! and println! macros. These macros allow you to display text, variables, and expressions in the console. The main difference between print! and println! is that println! adds a newline character at the end of the output, causing the next output to start on a new line, while print! does not.
Here's how you can use these macros:
let name = "Alice";
let age = 30;
print!("Name: ");
print!("{}", name);
println!(" is {} years old.", age);
println!("Hello, {}!", name);This code will produce the following output:
Name: Alice is 30 years old.
Hello, Alice!Challenge
BeginnerWrite a Rust program that uses print! and println! macros to output the following:
- Print
"Hello, "and"Coddy!"on the same line. - Print
"Rust is fun!"on a new line usingprintln!.
Use the given variables inside the print macros.
Cheat sheet
In Rust, use print! and println! macros to display output to the console:
print!- prints without adding a newlineprintln!- prints and adds a newline at the end
Use {} as placeholders for variables:
let name = "Alice";
let age = 30;
print!("Name: ");
print!("{}", name);
println!(" is {} years old.", age);
println!("Hello, {}!", name);Output:
Name: Alice is 30 years old.
Hello, Alice!Try it yourself
fn main() {
let hello = "Hello, ";
let coddy = "Coddy!";
let rust_is_fun = "Rust is fun!";
// Write your code below
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 33Variables Part 2
Type DeclarationNaming ConventionsType InferenceRecap - Initialize VariablesType Casting9Loops
For Over SeriesWhile LoopBreakContinueNested LoopLoop LabelsInfinite LoopRecap - Dynamic Input