Match VarError When Reading Environment
Classify environment lookups with env::var's Result: NotPresent means the key is missing, NotUnicode means the value cannot be read as a String.
Code
use std::env;
// env::var 返回 Result:键缺失、含非法 Unicode 是两类独立失败
fn read_token() -> Result<String, String> {
match env::var("AUTH_TOKEN_EXAMPLE") {
Ok(value) if value.len() >= 8 => Ok(value),
Ok(_) => Err("token too short".into()),
Err(env::VarError::NotPresent) => Err("AUTH_TOKEN_EXAMPLE not set".into()),
Err(env::VarError::NotUnicode(bad)) => Err(format!("not unicode: {bad:?}")),
}
}
fn main() {
match read_token() {
Ok(token) => println!("token loaded, {} chars", token.len()),
Err(reason) => println!("fallback: {reason}"),
}
// 探测式读取:同一套 VarError 分类适用于任何键
match env::var("CI_EXAMPLE_FLAG") {
Ok(value) => println!("flag present: {value:?}"),
Err(e) => println!("flag absent: {e}"),
}
}Inside the snippet
Count the functions read_token and main as the entire surface area of Match VarError When Reading Environment.
Fallible operations return Result, forcing the caller to handle both arms explicitly. The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.
What to watch for
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Putting it to use
Signature: fn read_token() -> Result<String, String>
Running the file prints labeled results such as token loaded,, fallback:, flag present: — each operation’s effect is visible in the output.
Execute the file and main walks through read_token, in that order.
Core lines
match env::var("AUTH_TOKEN_EXAMPLE") {
Ok(value) if value.len() >= 8 => Ok(value),
Ok(_) => Err("token too short".into()),
Err(env::VarError::NotPresent) => Err("AUTH_TOKEN_EXAMPLE not set".into()),
Err(env::VarError::NotUnicode(bad)) => Err(format!("not unicode: {bad:?}")),
}
match env::var("CI_EXAMPLE_FLAG") {
Ok(value) => println!("flag present: {value:?}"),
Err(e) => println!("flag absent: {e}"),
}
match read_token() {
Ok(token) => println!("token loaded, {} chars", token.len()),
Err(reason) => println!("fallback: {reason}"),
}
Interactive Tools for This Topic
FAQ
- How are errors reported?
- Each fallible operation returns `Result`; nothing is silently discarded.
- What does Match VarError When Reading Environment print when run?
- The script runs standalone; its 4 labeled outputs include `token loaded,`, `fallback:`, `flag present:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.