Propagate Missing Values With Option Question Mark
Propagate a missing field through an Option-returning function with the question-mark operator, so one absent value collapses the whole lookup.
Code
struct Profile {
name: Option<String>,
email: Option<String>,
team: Option<String>,
}
// 返回 Option 的函数里,? 传播 None:任何一个缺项整个查找落空
fn contact_line(profile: &Profile) -> Option<String> {
let name = profile.name.as_deref()?;
let email = profile.email.as_deref()?;
let team = profile.team.as_deref()?;
Some(format!("{team} <{email}> ({name})"))
}
fn main() {
let complete = Profile {
name: Some("ada".into()),
email: Some("[email protected]".into()),
team: Some("platform".into()),
};
let incomplete = Profile { name: Some("bob".into()), email: None, team: None };
println!("complete -> {:?}", contact_line(&complete));
println!("incomplete -> {:?}", contact_line(&incomplete));
}What the code does
Propagate Missing Values With Option Question Mark keeps everything in the functions contact_line and main.
Using it
Entry signature: fn contact_line(profile: &Profile) -> Option<String>
The demo output is labeled (complete ->, incomplete ->), so every printed line maps back to its originating operation.
The entry point wires contact_line together — run it once and the whole demo flows.
Key statements
let incomplete = Profile { name: Some("bob".into()), email: None, team: None };
fn contact_line(profile: &Profile) -> Option<String> {
let name = profile.name.as_deref()?;
let email = profile.email.as_deref()?;
let team = profile.team.as_deref()?;
Some(format!("{team} <{email}> ({name})"))
}
Interactive Tools for This Topic
FAQ
- What does Propagate Missing Values With Option Question Mark print when run?
- Execute the whole file; each printed line is prefixed with a label like `complete ->`, `incomplete ->`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.