Io::stdout()::lock() Is there a way to unlock this before it gets out of scope?
⚓ Rust 📅 2026-05-05 👤 surdeus 👁️ 2Hi everyone!
I'm completely new to Rust. I've read the crate book and a few pages from the main Rust book. I've also tried simple examples from those books.
use ferris_says::say;
use std::io::{stdout, BufWriter};
use regex::Regex;
fn main() {
//{ // <= if I do not add this phantom scope, then first output "Did our..." from println! macros
let stdout = stdout();
let message = String::from("Hello fellow Rustaceans");
let width = message.chars().count();
let mut writer = BufWriter::new(stdout.lock()); // <= here I lock io::stdout()
say(&message, width, &mut writer).unwrap(); // can I unlock here or something else?
//} // <= if I do not add this phantom scope, then first output "Did our..." from println! macros
let re = Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap(); // expected output second (last), but..
println!("Did our date match? {}", re.is_match("2026-05-05"));
}
Output for example above
nullpwr@mini hello-rust % cargo run
Compiling hello-rust v0.1.0 (/Volumes/source/github/nullpwr/hello-rust)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.47s
Running `target/debug/hello-rust`
Did our date match? true /// <= must be output as second string
_________________________
< Hello fellow Rustaceans >
-------------------------
\
\
_~^~^~_
\) / o o \ (/
'_ - _'
/ '-----' \
Can someone explain what I did wrong? If I'm already blocking with stdout.lock(), and the println! macro also blocks stdout, why aren't they the same stdout?
And what's the correct way to avoid these logical errors? Maybe I should use unlock, or is phantom scope acceptable? Maybe I should read more books?
I tried to fully comment the code above (as I understand it).
Thanks in advance!
5 posts - 3 participants
🏷️ Rust_feed