In my food platform there are specific categories which a restaurant can have. A restaurant can be in multiple categories.
I retrieve the following form to add a restaurant:
#[derive(Deserialize)]
pub struct AddRestaurantForm {
//...
pub restaurant_categories: std::vec::Vec<String>,
}
when a JSON-request is sent:
{
//...
"restaurant_categories":["sushi","italian"]
}
The different categories are in a enum
:
#[derive(Deserialize, Serialize, Clone, Debug)]
pub enum RestaurantCategory {
Sushi,
Italian,
Pizza,
Kebab,
}
impl FromStr for RestaurantCategory {
type Err = ();
fn from_str(input: &str) -> Result<RestaurantCategory, Self::Err> {
match &*input.to_lowercase() {
"sushi" => Ok(RestaurantCategory::Sushi),
"italian" => Ok(RestaurantCategory::Italian),
"pizza" => Ok(RestaurantCategory::Pizza),
"kebab" => Ok(RestaurantCategory::Kebab),
_ => Err(()),
}
}
}
The Restaurant struct:
#[derive(Deserialize, Serialize, Clone)]
pub struct Restaurant {
//...
categories: std::vec::Vec<RestaurantCategory>,
}
I need to convert the strings I retrieve in JSON to the enum
-values so I can input them in the categories
vec of a Restaurant
. Right now I do it like this:
let mut categories = std::vec::Vec::new();
for category in form.restaurant_categories.clone().into_iter() {
categories.push(RestaurantCategory::from_str(&category).unwrap());
}
let restaurant = Restaurant {
//...
categories: categories,
};
But I was wondering if there was a way to write this more elegant? Could I use some kind of map
-function to make the for-loop unnecessary?
E.g (pseudo-code):
let restaurant = Restaurant {
//...
categories: form.restaurant_categories.map(category => category.RestaurantCategory::from_str(&category).unwrap())
};
Basically I am just asking if there is a way to write this more elegant/efficient:
let mut categories = std::vec::Vec::new();
for category in form.restaurant_categories.clone().into_iter() {
categories.push(RestaurantCategory::from_str(&category).unwrap());
}
let restaurant = Restaurant {
//...
categories: categories,
};
What I tried:
let restaurant = Restaurant {
id: 0,
name: form.restaurant_name.to_string(),
email: form.restaurant_email.to_string(),
address: form.address.clone(),
dishes: std::vec::Vec::new(),
categories: form
.restaurant_categories
.clone()
.iter()
.map(|x| RestaurantCategory::from_str(x).unwrap()),
image: None,
};