Rust chapters

Chapter 15 of 17

Input, Output and Files

Try this in our Rust Compiler →

Talking to the world

A useful program reads input (from the keyboard, a file, a network call, or another program) and produces output (to the screen, a file, or another network call). Rust provides simple helpers for the basic cases and powerful libraries for the rest.

use std::io::{self, BufRead};
let mut line = String::new();
io::stdin().lock().read_line(&mut line).unwrap();
println!("Hello, {}", line.trim());

Buffering and performance

Reading or writing one byte at a time is usually slow. Rust buffers I/O behind the scenes so that small reads and writes are batched into larger ones. When you need maximum performance — large log files, streaming uploads — drop down to the buffered or streaming APIs explicitly.

Closing resources

Files, sockets and database connections must be closed when you are done with them. Forgetting leaks operating-system resources and eventually crashes long-running programs. Use the language's built-in with / using / defer construct (it has a different name in each language) to guarantee cleanup happens.

Details for rust

read_line appends to a String, so clear it between independent reads. trim removes meaningful surrounding spaces too. split_whitespace separates tokens before parse. Local module files must be included; standalone rustc does not imply Cargo dependencies.

Practice and verify

Read two numbers from supplied stdin and print their sum. Input 10 and 20 should produce 30. Test missing tokens separately from malformed numbers; preserve text until deliberately parsing it.

Try it yourself

Output
Run your project to see output here.
Ctrl/Cmd+Enter runs · Ctrl/Cmd+S downloads the project · Local auto-save is always on