How it works...

We first created an enum type named Food that had data elements, namely Apple, Carrot, and Potato. Then we created three struct with user-defined data types, namely Peeled, Chopped, and Cooked with Food as a data field. In the main function, we created three variables and assigned them to the values of the Option data, where apple was valued Food::Apple, carrot as Food::Carrot, and potato as None.

Now let's check out how our function units react to different input:

  • peel: This function takes in an Option type that has a field enum type Food along with the data and returns an Option of the struct data type Peeled. Here we use the match function to change the type.
  • chop: This function takes in the Option type that has a field enum type Peeled along with the data and returns an Option of the struct data type Chopped. Here we use the match function to change the type.
  • cook: This function takes in the Option type that has a field enum type Chopped along with the data and returns an Option of the struct data type Cooked. Here we use the map function to change the type, where we place the input type between two pipe symbols that convert them into the desired form.
  • process: Instead of having three functions to change types, we use map multiple times to convert Option<Food> into Option<Cooked> directly, where each map function successively converts the type to the desired form by this process we can peel, chop, and cook food type in a sequence by using multiple map(), thus it simplifies the code.
  • eat: This function takes in the Option<Cooked> type as an input argument and checks it using a match statement. The first case some(food) would be true if a valid type exists for the food argument which is passed to the match statement, then it would print the value of the argument food in the place holder of the print statement else in the None case, it prints a default statement.

In the main function, we declared cooked_apple and assigned the return value of the chop(peel(apple)) call. Since we didn't pass a None input, this was supposed to return the Cooked(apple) type of the data feed. Similarly, cooked_carrot had the value Cooked(carrot); however, cooked_potato, for which we called the process function, returned None. Later, when we called the eat function, only the variable that had Cooked struct values got printed as MM. I Love statement and the variable that had None had Oh No! statement.

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

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