get_or_insert Defaults An Option In Place
Insert defaults into Options in place: get_or_insert writes only when empty, get_or_insert_with defers the cost, and both return a mutable reference.
Code
#[derive(Debug)]
struct Settings {
theme: Option<String>,
retries: Option<u32>,
}
impl Settings {
// 就地补默认值:None 才写入,Some 原样保留
fn resolve(mut self) -> Self {
self.theme.get_or_insert(String::from("dark"));
// 带构造成本的默认值交给 get_or_insert_with:Some 时不会执行
self.retries.get_or_insert_with(|| 5);
self
}
}
fn main() {
let partial = Settings { theme: Some(String::from("light")), retries: None };
println!("{:?}", partial.resolve());
let empty = Settings { theme: None, retries: None };
println!("{:?}", empty.resolve());
// 返回的是 &mut T:可以直接修改刚放入的值
let mut token: Option<String> = None;
let slot = token.get_or_insert(String::from("temp"));
slot.push_str("-session");
println!("{}", token.as_deref().unwrap());
}How the snippet works
get_or_insert Defaults An Option In Place keeps everything in the functions resolve and main.
Applying it
The main signature reads fn resolve(mut self) -> Self
The entry point wires resolve together — run it once and the whole demo flows.
Statements that matter
let partial = Settings { theme: Some(String::from("light")), retries: None };
let empty = Settings { theme: None, retries: None };
let mut token: Option<String> = None;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- How do you run get_or_insert Defaults An Option In Place?
- Direct execution is enough; the script has no external requirements.
Report a problem with this exampleOpens a pre-filled issue on GitHub.