Optional arguments

I am trying to initialize a structure with optional arguments but I can't

error[E0277]: the trait bound `std::string::String: std::convert::From<std::option::Option<std::string::String>>` is not satisfied
  --> src/main.rs:11:44
   |
11 |             description: Some(String::from(description))
   |                                            ^^^^^^^^^^^ the trait `std::convert::From<std::option::Option<std::string::String>>` is not implemented for `std::string::String`
   |

what would be the correct way to do this?

#[derive(Debug)]
pub struct Car {
    model: String,
    description: Option<String>,
}

impl Car{
    pub fn new(model: String, description: Option<String>) -> Self {
         Self {
            model: String::from(model),
            description: Some(String::from(description))
        }
    } 
} 


pub fn main() {
    
    let car1  = Car::new(String::from("Mazda"), Some(String::from("test")));
    
    println!("Car {:?}", car1);
    
}

model and description already have the correct types, so you don't need to use String::from to convert them. This should work:

    pub fn new(model: String, description: Option<String>) -> Self {
         Self { model, description }
    } 
2 Likes