← 中文资源

简体中文版本

问号运算符传播 Option 缺项

返回 Option 的函数里 ? 会传播 None:任何一个可选字段缺失,整条查找链立即落空,避免逐层手写 match 嵌套。

阅读英文原文

实现说明

全部逻辑都在函数 contact_line、main中。

使用要点

  • 每一步打印都带着自己的标签:complete ->、incomplete ->。
  • main 按顺序串起 contact_line;运行文件就会把这个流程跑一遍。

常见问题

运行「问号运算符传播 Option 缺项」会打印什么?

整个文件跑完,输出行以 complete ->、incomplete -> 这类前缀开头。

签名一览:fn contact_line(profile: &Profile) -> Option<String>

核心语句

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})"))
}

代码示例

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));
}