#ternary #operator #inline #if

ternop

A tiny macro that implements a ternary operator for Rust

1 stable release

Uses old Rust 2015

1.0.1 Dec 2, 2017

#8 in #if

Download history 439/week @ 2024-08-09 339/week @ 2024-08-16 490/week @ 2024-08-23 616/week @ 2024-08-30 482/week @ 2024-09-06 246/week @ 2024-09-13 353/week @ 2024-09-20 538/week @ 2024-09-27 371/week @ 2024-10-04 317/week @ 2024-10-11 497/week @ 2024-10-18 396/week @ 2024-10-25 295/week @ 2024-11-01 534/week @ 2024-11-08 293/week @ 2024-11-15 656/week @ 2024-11-22

1,833 downloads per month
Used in 5 crates (via mailin)

MIT/X11 license

3KB

Ternary Operator

Rust doesn't support return (condition) ? if_true : if_false;. This crate exports a macro that implements this feature.

fn is_ipv4(val: &str) -> i32 {
    ternary!(val == "ipv4", 4, 16)
}

If you just want to copy the small macro, here you go 😅

#[macro_export]
macro_rules! ternary {
    ($condition: expr, $_true: expr, $_false: expr) => {
        if $condition { $_true } else { $_false }
    };
}

lib.rs:

A dead simple ternary operator macro which allows you to write quick one-line returnes for a variety of types.

Examples

To use the ternary operator just invoke the ternary macro

fn is_ipv4(val: &str) -> i32 {
    ternary!(val == "ipv4", 4, 16)
}

No runtime deps