Rust Tutorials: Boolean Type (`bool`) šŸŽÆ

beginner
12 min

Rust Tutorials: Boolean Type (bool) šŸŽÆ

Welcome to the Rust Boolean Type tutorial! Today, we're going to learn about the bool type in Rust and explore its practical applications. By the end of this lesson, you'll have a solid understanding of bool and feel confident using it in your own projects. Let's dive in!

What is a Boolean Type? šŸ“

In Rust, the bool type represents a value that can be either true or false. It's commonly used in conditions, decisions, and logic in programming.

Why use Boolean Type? šŸ’”

Using the bool type allows us to write conditional logic in our programs, making them more dynamic and responsive to user input or external conditions.

Creating Boolean Variables šŸ’”

Creating a bool variable in Rust is as simple as assigning a value of either true or false.

rust
let is_day_time = true; let is_hot_outside = false;

šŸ“ Note: Variable names in Rust are always snake_case, meaning we use underscores to separate words.

Operators for Boolean Type šŸ’”

There are several operators in Rust that work with bool values. Let's take a look at some of them:

Comparison Operators šŸ’”

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)
rust
let number_one = 5; let number_two = 10; let is_equal = number_one == number_two; // false let is_not_equal = number_one != number_two; // true

Logical Operators šŸ’”

  • && (logical AND)
  • || (logical OR)
  • ! (logical NOT)
rust
let is_raining = true; let is_sunny = false; let is_inside = true; let is_wet = is_raining && is_inside; // true let is_outside = !is_inside; // false let is_dry_or_sunny = is_dry || is_sunny; // true

Boolean Functions šŸ’”

Rust also provides several built-in functions to work with bool values:

  • bool::to_string(): Converts a bool value to a string
  • bool::from_str(s: &str): Converts a string to a bool value
rust
let bool_value = true; let string_value = bool_value.to_string(); // "true" let input = "false"; let input_as_bool = bool::from_str(input); // false

Quiz šŸ’”

Quick Quiz
Question 1 of 1

What does the `bool` type represent in Rust?

Summary āœ…

In this lesson, we learned about the bool type in Rust, its purpose, and how to create and manipulate boolean variables. We also covered operators and functions that work with bool values. With this newfound knowledge, you're ready to write more expressive and dynamic Rust programs!

Stay tuned for our next tutorial, where we'll explore more Rust types and features. Happy coding! šŸŽ‰