pub fn ternary_operator<T>(condition: bool, if_true: T, if_false: T) -> TExpand description
Compacts the standard if (condition) {} else {} into a single call, to improve readability and please users accustomed to the ternary operator in other languages.
§Arguments
-
condition- A boolean value representing the condition to check. -
if_true- The value returned if theconditionis true. -
if_false- The value returned if theconditionis false.§Notes
- The type of
if_trueandif_falsemust be the same.
This function allows you to use any type for the
if_trueandif_falsearguments, but it requires both arguments to be of the same type. - The type of
§Returns
The result of the ternary operation, which is either if_true or if_false, depending on the condition’s result.
§Panics
This function does not panic under normal circumstances.
§Examples
In these examples, the ternary_operator function is used to make decisions based on different conditions, types, and nesting scenarios.
Remember that while the function provides flexibility, excessive nesting might affect code readability.
-
Applying a discount based on age:
use rusty_utils::ternary_operator; fn calculate_discount(price: f32, age: u32) -> f32 { const ELIGIBLE_AGE: u32 = 60; const DISCOUNT_PERCENTAGE: f32 = 0.10; let discount = ternary_operator(age > ELIGIBLE_AGE, DISCOUNT_PERCENTAGE, 0.0); price * (1.0 - discount) } let price = 100.0; let discounted_price = calculate_discount(price, 65); assert_eq!(discounted_price, 90.0); let regular_price = calculate_discount(price, 50); assert_eq!(regular_price, 100.0);
-
Selecting a type dynamically:
use rusty_utils::ternary_operator; fn get_default<T: Default>(value: Option<T>) -> T { ternary_operator(value.is_some(), value.unwrap_or_default(), T::default()) } let integer_value: Option<i32> = Some(42); let result_int = get_default(integer_value); assert_eq!(result_int, 42); let string_value: Option<&str> = None; let result_str = get_default(string_value); assert_eq!(result_str, "");
-
Deciding based on boolean conditions:
use rusty_utils::ternary_operator; fn is_even_or_odd(number: i32) -> &'static str { ternary_operator(number % 2 == 0, "Even", "Odd") } assert_eq!(is_even_or_odd(4), "Even"); assert_eq!(is_even_or_odd(7), "Odd");
-
Combining conditions with nesting (not recommended for readability):
use rusty_utils::ternary_operator; fn complicated_calculation(a: i32, b: i32, use_a: bool) -> i32 { ternary_operator(use_a, ternary_operator(b > 0, a, 0), 2) } assert_eq!(complicated_calculation(1, -1, true), 0); assert_eq!(complicated_calculation(1, -1, false), 2);