Home
Map
bool Functions, Return True and FalseSpecify that a function returns bool and compute the result with an expression.
Rust
This page was last reviewed on May 28, 2021.
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.
Detail The is_current function receives an Employee, and returns a bool. The bool is true if the expression evaluates to true.
Detail This bool function returns true if is_current returns true, and the salary field is high.
Detail 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).
A summary. 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 28, 2021 (new).
Home
Changes
© 2007-2024 Sam Allen.