实现说明
全部逻辑都在函数 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("ada@example.com".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));
}