Читаем Rust by Example полностью

// Check whether there's food or not before trying to eat it!

fn eat(food: Option) {

match food {

Some(food) => println!("Mmm. I love {:?}", food),

None => println!("Oh no! It wasn't edible."),

}

}

fn main() {

let apple = Some(Food::Apple);

let carrot = Some(Food::Carrot);

let potato = None;

let cooked_apple = cook(chop(peel(apple)));

let cooked_carrot = cook(chop(peel(carrot)));

// Let's try the simpler looking `process()` now.

let cooked_potato = process(potato);

eat(cooked_apple);

eat(cooked_carrot);

eat(cooked_potato);

}

הההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההההה

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

<p id="see_also_60"><strong><a l:href="#see_also_60">See also:</a></strong></p>

closures, Option, Option::map()

<p id="combinators_and_then"><strong><a l:href="#combinators_and_then">Combinators:</a><a l:href="#combinators_and_then">and_then</a></strong></p>

map() was described as a chainable way to simplify match statements. However, using map() on a function that returns an Option results in the nested Option>. Chaining multiple calls together can then become confusing. That's where another combinator called and_then(), known in some languages as flatmap, comes in.

and_then() calls its function input with the wrapped value and returns the result. If the Option is None, then it returns None instead.

In the following example, cookable_v2() results in an Option. Using map() instead of and_then() would have given an Option>, which is an invalid type for eat().

#![allow(dead_code)]

#[derive(Debug)] enum Food { CordonBleu, Steak, Sushi }

#[derive(Debug)] enum Day { Monday, Tuesday, Wednesday }

// We don't have the ingredients to make Sushi.

fn have_ingredients(food: Food) -> Option {

match food {

Food::Sushi => None,

_ => Some(food),

}

}

// We have the recipe for everything except Cordon Bleu.

fn have_recipe(food: Food) -> Option {

match food {

Food::CordonBleu => None,

_ => Some(food),

}

}

// To make a dish, we need both the recipe and the ingredients.

// We can represent the logic with a chain of `match`es:

fn cookable_v1(food: Food) -> Option {

match have_recipe(food) {

None => None,

Some(food) => match have_ingredients(food) {

None => None,

Some(food) => Some(food),

},

}

}

// This can conveniently be rewritten more compactly with `and_then()`:

fn cookable_v2(food: Food) -> Option {

have_recipe(food).and_then(have_ingredients)

}

fn eat(food: Food, day: Day) {

match cookable_v2(food) {

Перейти на страницу:

Похожие книги