Match Borrowed Options With As Ref And As Deref
Convert Option<String> into Option<&str> with as_deref before matching so arms compare string literals while the owned value stays usable afterward.
Code
fn lookup(key: &str) -> Option<String> {
// 模拟环境存储:值都是拥有所有权的 String
match key {
"log-level" => Some("verbose".to_string()),
"region" => Some("eu-west-1".to_string()),
"label" => Some(String::new()),
_ => None,
}
}
fn classify(value: Option<String>) -> &'static str {
// as_deref:Option<String> -> Option<&str>,借用而不移动
match value.as_deref() {
None => "unset",
Some("") => "empty", // &str 可直接与字面量比较
Some("verbose") => "loud",
Some(other) if other.len() > 8 => "long value",
Some(_) => "ordinary",
}
}
fn main() {
for key in ["log-level", "region", "label", "missing"] {
let raw = lookup(key);
println!("{key}: {}", classify(raw));
}
// 借用的证据:as_deref 之后原值仍然完好
let owner = Some(String::from("region"));
if let Some(text) = owner.as_deref() {
println!("borrowed: {text}");
}
println!("still owned: {:?}", owner);
}How it works
Match Borrowed Options With As Ref And As Deref keeps everything in the functions lookup, classify and main.
Iteration happens inside for key in ["log-level", "region", "label", "missing"] — everything outside it runs once. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.
Applying it
The primary signature is fn lookup(key: &str) -> Option<String>
The file announces its steps in the output: borrowed:, still owned:.
main sequences lookup and classify; executing the file runs that flow once.
Statements that matter
Some("") => "empty", // &str 可直接与字面量比较
Some("verbose") => "loud",
Some(other) if other.len() > 8 => "long value",
Some(_) => "ordinary",
}
let owner = Some(String::from("region"));
fn lookup(key: &str) -> Option<String> {
// 模拟环境存储:值都是拥有所有权的 String
match key {
"log-level" => Some("verbose".to_string()),
"region" => Some("eu-west-1".to_string()),
"label" => Some(String::new()),
_ => None,
}
}
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- What does Match Borrowed Options With As Ref And As Deref print when run?
- Execute the whole file; each printed line is prefixed with a label like `borrowed:`, `still owned:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.