Concatenate optional value

Hello
I tried to Concatenate a string with an optional one but it doesn't work for me

#[derive(Clone, Hash, Debug, PartialEq)]
struct PersonalName {
    first_name: String,
    last_name: Option<String>,
}

impl PersonalName {
    fn full_name(&self) -> String {

        let ln = Some(self.last_name.as_ref().unwrap());
        match ln {
            Some(v) => format!("{} {}", self.first_name, v),
            _ => self.first_name.to_string(),
        }
    }
}


fn main() {
  let a = PersonalName{
      first_name: "Jhon".to_string(),
      //last_name: Some("Smith".to_string()),
    }; 
    
    println!("Hello {}", a.full_name());
}
   Compiling playground v0.0.1 (/playground)
error[E0063]: missing field `last_name` in initializer of `PersonalName`
  --> src/main.rs:24:11
   |
24 |   let a = PersonalName{
   |           ^^^^^^^^^^^^ missing `last_name`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0063`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

To initialize a struct you should provide all its fields, or call another function which does so for you. Option<T> is not a magical language construct but an ordinary enum type.

let a = PersonalName {
    first_name: "Jhon".to_string(),
    last_name: None,
};
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.