Why does print!() statement runs after the execution of read_string() in the ask_for_a_string/number() function
⚓ Rust 📅 2025-11-07 👤 surdeus 👁️ 3struct Person {
first_name: String,
last_name: String,
age: u8,
}
fn main() {
let first_name = ask_for_a_string("What is your first name?");
let last_name = ask_for_a_string("What is your last name?");
let age = ask_for_a_number("How old are you?").unwrap_or(0);
let person = Person {
first_name,
last_name,
age,
};
println!(
"{}\n{}\n{}",
person.first_name, person.last_name, person.age
);
}
use std::str::FromStr;
fn read_string() -> String {
let mut input = String::new();
std::io::stdin()
.read_line(&mut input)
.expect("can not read user input");
input.trim().to_string()
}
fn read_number() -> Result<u8, String> {
let input = read_string();
if input.is_empty() {
Err("You did not enter any data".to_string())
} else {
u8::from_str(&input).or(Err("You've entered an invalid number".to_string()))
}
}
fn ask_for_a_string(question: &str) -> String {
print!("{} ", question);
read_string()
}
fn ask_for_a_number(question: &str) -> Result<u8, String> {
print!("{} ", question);
read_number()
}
Output:
What is your first name? What is your last name? How old are you? h
q
1
Errors:
Compiling playground v0.0.1 (/playground)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.74s
Running `target/debug/playground`
2 posts - 2 participants
🏷️ Rust_feed