Home
Rust
return bool Functions (True and False)
Updated Mar 6, 2025
Dot Net Perls
Bool function. 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.
Struct use. 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.
Example code. To start, consider this Rust program. We introduce an Employee struct, with has 3 fields—an integer, and 2 bool fields.
Start The is_current function receives an Employee, and returns a bool. The bool is true if the expression evaluates to true.
Next The is_executive bool function returns true if is_current returns true, and the salary field is high.
Info We create 2 Employee 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
Expressions. Consider the way the functions returns expressions based on the "and" operator. This style of code is clear. It combines multiple conditions into one.
Is prefix. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 6, 2025 (edit).
Home
Changes
© 2007-2025 Sam Allen