연습 - Option 형식을 사용하여 부재 처리
이 연습에서는 Person
구조체를 받아서 사람의 전체 이름이 포함된 String
을 반환하는 함수를 최종적으로 구현합니다.
중간 이름이 없는 사람도 있지만, 있는 경우 중간 이름이 반환 값에 포함되어야 합니다.
build_full_name
함수만 편집해야 합니다. 성과 이름을 처리하는 부분은 이미 구현되어 있습니다.
struct Person {
first: String,
middle: Option<String>,
last: String,
}
fn build_full_name(person: &Person) -> String {
let mut full_name = String::new();
full_name.push_str(&person.first);
full_name.push_str(" ");
// TODO: Implement the part of this function that handles the person's middle name.
full_name.push_str(&person.last);
full_name
}
fn main() {
let john = Person {
first: String::from("James"),
middle: Some(String::from("Oliver")),
last: String::from("Smith"),
};
assert_eq!(build_full_name(&john), "James Oliver Smith");
let alice = Person {
first: String::from("Alice"),
middle: None,
last: String::from("Stevens"),
};
assert_eq!(build_full_name(&alice), "Alice Stevens");
let bob = Person {
first: String::from("Robert"),
middle: Some(String::from("Murdock")),
last: String::from("Jones"),
};
assert_eq!(build_full_name(&bob), "Robert Murdock Jones");
}
위의 코드를 실행하고 모든 assert_eq!
식이 패닉 없이 통과하는지 확인합니다. Rust 플레이그라운드에서 코드를 편집할 수도 있습니다.
이 연습의 솔루션을 받으세요.