From 60947aaacded78b38f68b5b8cef1d76bd913ad21 Mon Sep 17 00:00:00 2001 From: Luca Palmieri <20745048+LukeMathWalker@users.noreply.github.com> Date: Wed, 18 Dec 2024 16:53:14 +0100 Subject: [PATCH] Showcase else-if (#234) --- book/src/02_basic_calculator/03_if_else.md | 32 ++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/book/src/02_basic_calculator/03_if_else.md b/book/src/02_basic_calculator/03_if_else.md index 3a6acfc..44a1270 100644 --- a/book/src/02_basic_calculator/03_if_else.md +++ b/book/src/02_basic_calculator/03_if_else.md @@ -36,6 +36,38 @@ if number < 5 { } ``` +### `else if` clauses + +Your code drifts more and more to the right when you have multiple `if` expressions, one nested inside the other. + +```rust +let number = 3; + +if number < 5 { + println!("`number` is smaller than 5"); +} else { + if number >= 3 { + println!("`number` is greater than or equal to 3, but smaller than 5"); + } else { + println!("`number` is smaller than 3"); + } +} +``` + +You can use the `else if` keyword to combine multiple `if` expressions into a single one: + +```rust +let number = 3; + +if number < 5 { + println!("`number` is smaller than 5"); +} else if number >= 3 { + println!("`number` is greater than or equal to 3, but smaller than 5"); +} else { + println!("`number` is smaller than 3"); +} +``` + ## Booleans The condition in an `if` expression must be of type `bool`, a **boolean**.\