Introduction
Rust provides the println! and print! macros for writing formatted output to the console, using curly braces {} as placeholders for values. For reading input, Rust uses the standard library's std::io module, most commonly via std::io::stdin().read_line(&mut buffer) to capture a line of text, which is then typically parsed into the desired type using .trim().parse() combined with error handling.
Cricket analogy: Announcing the score with println! is like a commentator reading out "{} for {}" placeholders filled with runs and wickets, while capturing a player's shouted target via stdin().read_line(&mut buffer) needs trim().parse() to convert the scribbled note into a usable number.
Syntax
use std::io;
// Output
println!("Hello, {}!", "world");
print!("No newline here");
// Input
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let number: i32 = input.trim().parse().expect("Not a number");Explanation
The println! macro appends a newline after printing, while print! does not; both support {} placeholders that are replaced by the arguments in order, and {:?} for debug-formatting values like tuples or vectors. Reading input requires creating a mutable String buffer and passing it by mutable reference to read_line, which appends the user's input including the trailing newline character. Because read_line returns a Result, it's common to call .expect(...) to handle potential errors, or use proper match/if let error handling in production code. Since input is always read as a String, converting it to a number requires .trim() to remove whitespace and the newline, followed by .parse() to convert it into the target numeric type, which itself returns a Result that must be handled.
Cricket analogy: println! ends each commentary line with a break like an over completing, while print! keeps commentary flowing mid-over; {:?} debug-prints a whole scoreboard tuple at once, and reading a shouted score via read_line grabs a trailing newline that must be trimmed before parse() converts it, itself returning a Result you .expect() or match on.
Example
use std::io;
fn main() {
println!("Enter your age:");
let mut input = String::new();
io::stdin()
.read_line(&mut input)
.expect("Failed to read line");
let age: u32 = match input.trim().parse() {
Ok(num) => num,
Err(_) => {
println!("Invalid number, defaulting to 0");
0
}
};
println!("In 5 years you will be {} years old.", age + 5);
}Output
Enter your age:
25
In 5 years you will be 30 years old.Key Takeaways
- println! adds a trailing newline; print! does not.
- Curly braces {} are placeholders for formatted values in output macros.
- std::io::stdin().read_line(&mut buffer) reads a line of text into a String.
- Input includes a trailing newline, so .trim() should be called before parsing.
- .parse() converts a string into a numeric type and returns a Result that should be handled.
Practice what you learned
1. What is the difference between println! and print! in Rust?
2. Which function is commonly used to read a line of input from the console in Rust?
3. Why is `.trim()` typically called on input before parsing it into a number?
4. What does the `.parse()` method return when converting a String to a number?
5. Which placeholder syntax is used inside println! for inserting formatted values?
Was this page helpful?
You May Also Like
Variables and Data Types in Rust
Learn how Rust variables are immutable by default and explore its scalar and compound data types.
Type Conversion in Rust
Learn how Rust handles explicit type conversion using the as keyword and the From/Into traits.
Error Handling in Rust (Result)
Learn how Rust models recoverable errors with the Result enum and the ? operator instead of exceptions.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics