How to do it...

Follow these steps to get through this recipe:

  1. Create a file named sample_and_then.rs and open it in your text editor.
  2. Write the code header with the relevant information:
        //-- #########################
//-- Task: Implementing and_then
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 26 March 17
//-- #########################
  1. Create the enum types Food and Day:
        #![allow(dead_code)]

#[derive(Debug)] enum Food { CordonBleu, Steak, Sushi}
#[derive(Debug)] enum Day { Monday, Tuesday, Wednesday}
  1. Define a function named have_ingredients that will accept the Food type as an input argument and return Option<Food>:
        fn have_ingredients(food: Food) -> Option<Food> {
match food {
Food::Sushi => None,
_ => Some(food),
}
}
  1. Define a function named have_recipe that will accept the Food type as an input argument and return Option<Food>:
        fn have_recipe(food: Food) -> Option<Food> {
match food {
Food::CordonBleu => None,
_ => Some(food),
}
}
  1. Define a function named cookable that will accept the Food type as an input argument and return Option<Food>:
        fn cookable(food: Food) -> Option<Food> {
have_ingredients(food).and_then(have_recipe)
}
  1. Define a function named eat that will accept the Food type as an input argument and return Day:
        fn eat(food: Food, day: Day) {
match cookable(food) {
Some(food) => println!("Yay! On {:?} we get to eat
{:?}.", day, food),
None => println!("Oh no. We don't get to eat on
{:?}?", day),
}
}
  1. Define the main function; it will initialize and call all the functions:
        fn main() {
let (cordon_bleu, steak, sushi) = (Food::CordonBleu,
Food::Steak, Food::Sushi);

eat(cordon_bleu, Day::Monday);
eat(steak, Day::Tuesday);
eat(sushi, Day::Wednesday);
}

You will get the following output upon successful execution of the code:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.235.188