Rust Bool Functions, Return True and FalseSpecify that a function returns bool and compute the result with an expression.
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.
Current The is_current function receives an Employee, and returns a bool. The bool is true if the expression evaluates to true.
Executive This bool function returns true if is_current returns true, and the salary field is high.
Main We create 2 Employee struct instances, and test them with the bool returning functions.
Rust program that uses bool return 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 "&&" 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.
© 2007-2021 sam allen. see site info on the changelog