3 ms·
This is way off topic but 2 hours ago I was trying to figure out how to read a single line from stdio using Rust/tokio and failed to figure it out in a reasonab
by apitman 2y ago
This is way off topic but 2 hours ago I was trying to figure out how to read a single line from stdio using Rust/tokio and failed to figure it out in a reasonable time. It was infuriating.
- kstrauser 2y agoI could stand to hear more about this. What problem were you running into?
- apitman 2y agoBasically googling "tokio read line" didn't lead me to uncle's solution.
- ComputerGuru 2y agolet mut line = String::new(); std::io::stdin().read_line(&mut line).unwrap(); And I just looked it up and it's right there in the docs, too: https://doc.rust-lang.org/std/io/struct.Stdin.html https://doc.rust-lang.org/std/io/struct.Stdin.html You basically shouldn't use `tokio::io::stdin()` for what you want, as is documented at https://docs.rs/tokio/latest/tokio/io/fn.stdin.html https://docs.rs/tokio/latest/tokio/io/fn.stdin.html > For interactive uses, it is recommended to spawn a thread dedicated to user input and use blocking IO directly in that thread. So the code under tokio would be let line = rt.spawn_blocking(|| { use std::io::stdin; let mut buffer = String::new(); stdin().read_line(&mut buffer).unwrap() }).await.unwrap();
- apitman 2y agoYeah std::io is what I ended up using, but it felt like I might be doing something wrong. Wasn't sure if using blocking IO would mess with tokio. Your answer seems to indicate that intuition was correct, and I should be wrapping it in spawn_blocking. That all makes sense, it would just be nice if your comment was at the top of the google search results.