Files, command lines, and data boundaries.
Follow external input from bytes to validated meaning.
The idea behind the syntax.
A program becomes a tool when it accepts input beyond values written in source code. Command-line arguments, environment variables, files, and network messages are all external data. Their existence, encoding, and shape can differ from expectation. Rust's Result types make that uncertainty visible, but the program still needs a clear policy for an absent path, an invalid number, or malformed content.
Separate three stages: obtain bytes, parse a representation, and validate the domain meaning. Reading a file into a String can fail because the file is missing or the bytes are not valid UTF-8. Parsing JSON can succeed while a required field is absent or semantically wrong. The distinctions matter because each failure suggests a different response to a user or caller.
What Rust is checking.
std::fs offers straightforward file operations, while std::io provides lower-level readers and writers for streams and large data. std::env exposes arguments and environment variables. Serialization libraries turn Rust values into formats such as JSON and back, but a type-shaped object is not automatically a valid business record. Network input needs the same validation as a local file.
A useful command-line boundary translates raw strings into a typed configuration once, near the start of the program. The rest of the code can then rely on validated paths and options instead of repeatedly parsing strings. Keep diagnostic output separate from a machine-readable result, and include enough context in an error to identify the failing input without exposing secrets. The examples show these boundaries at different layers.
See the rule in context.
Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.
Files, paths & buffered reading
Filesystem operations return Result because files may be missing, permissions may differ, and devices may fail. Path and PathBuf model platform paths without forcing them to be UTF-8 strings. read_to_string is convenient for small text files, while BufReader and BufRead::lines support streaming lines. Writing a path can truncate an existing file, so practice in a dedicated directory and make overwrite behavior part of the application contract. Return io::Result when the caller can handle filesystem failures.
use std::fs;
use std::io;
use std::path::Path;
fn main() -> io::Result<()> {
let path = Path::new("lab-note.txt");
fs::write(path, "build\ntest\n")?;
let content = fs::read_to_string(path)?;
println!("lines={}", content.lines().count());
fs::remove_file(path)?;
Ok(())
}lines=2
- The example writes only its named practice file in the current directory.
- ? propagates I/O errors to main.
- The file is removed after reading.
The boundary: read_to_string requires valid UTF-8 and loads the whole file. Use byte reads or buffered processing when the input contract differs.
Arguments, environment & exit codes
std::env::args reads UTF-8 command-line arguments, while args_os handles platform strings that may not be valid UTF-8. The first argument normally identifies the executable. Environment variables are optional process configuration, not a secure place to print secrets. Return clear errors and a nonzero exit code for failed operations. Manual argument parsing is suitable for a tiny exercise; the cookbook’s Clap project adds generated help, validation, and predictable options for a larger command-line interface.
fn parse_limit(args: &[&str]) -> Result<usize, String> {
match args {
[] => Ok(10),
[value] => value
.parse()
.map_err(|_| "expected a whole-number limit".into()),
_ => Err("expected at most one argument".into()),
}
}
fn main() {
println!("default={}", parse_limit(&[]).unwrap());
println!("custom={}", parse_limit(&["25"]).unwrap());
assert!(parse_limit(&["x"]).is_err());
}default=10 custom=25
- Parsing is isolated from process-global input so it can be tested.
- The empty argument list has an explicit default.
- Malformed values remain errors.
The boundary: args panics on non-UTF-8 process arguments. Use args_os when arbitrary filesystem paths are valid inputs.
Serialization & boundary validation
Serialization converts typed data into a transport representation; deserialization performs the reverse. Serde derives these operations for compatible types, with serde_json supplying JSON encoding. A syntactically valid JSON document can still violate your domain rules. Deserialize into an input type, validate length, range, and required relationships, then construct a domain value. The Axum task API cookbook demonstrates this full path with JSON input and status codes. Never build JSON or SQL by concatenating untrusted text.
#[derive(Debug, PartialEq)]
struct Title(String);
impl Title {
fn parse(raw: &str) -> Result<Self, &'static str> {
let value = raw.trim();
if value.is_empty() || value.chars().count() > 80 {
Err("title must contain 1–80 characters")
} else {
Ok(Self(value.to_owned()))
}
}
}
fn main() {
let title = Title::parse(" Build ").unwrap();
println!("{}", title.0);
assert!(Title::parse(" ").is_err());
}Build
- Parsing transport text and validating domain meaning are separate steps.
- Trim defines the accepted normalization policy.
- The owned Title can be passed beyond the input buffer’s lifetime.
The boundary: Character limits and byte limits serve different purposes. Apply both where network resource use and user-visible text length matter.
Keep this model.
External data crosses several boundaries. Successful reading and parsing are only steps toward a valid value your program can safely use.