An expression in Rust often evaluates to true or false. With a function that returns a bool
, we can test a condition in a reliable and clear way.
Programs are often built up from structs. By receiving a struct
(and borrowing the struct
) we can test fields on the struct
, and return true or false.
To start, consider this Rust program. We introduce an Employee struct
, with has 3 fields—an integer, and 2 bool
fields.
is_current
function receives an Employee, and returns a bool
. The bool
is true if the expression evaluates to true.is_executive
bool
function returns true if is_current
returns true, and the salary field is high.struct
instances, and test them with the bool
returning functions.#[derive(Debug)] struct Employee { salary: i32, hired: bool, fired: bool } fn is_current(employee: &Employee) -> bool { // Return true if Employee is current. return !employee.fired && employee.hired && employee.salary > 0; } fn is_executive(employee: &Employee) -> bool { // Return true if Employee is current, and has high salary. return is_current(employee) && employee.salary > 1000000; } fn main() { // Test the bool return functions. let employee1 = Employee { salary: 0, hired: false, fired: false }; println!("{:?}", employee1); let result1 = is_current(&employee1); println!("{}", result1); let employee2 = Employee { salary: 2000000, hired: true, fired: false }; println!("{:?}", employee2); let result2 = is_current(&employee2); println!("{}", result2); let executive2 = is_executive(&employee2); println!("{}", executive2); }Employee { salary: 0, hired: false, fired: false } false Employee { salary: 2000000, hired: true, fired: false } true true
Consider the way the functions returns expressions based on the "and" operator. This style of code is clear. It combines multiple conditions into one.
For functions in Rust that return true or false (bool
), we often use the "is" prefix as a naming convention. This is done in the standard library (like is_empty
on strings).
Returning true or false from functions is a helpful approach to developing complex logic. Rust programs often use bool
functions, even in the standard library.