#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

#2105 in Rust patterns

Download history 241/week @ 2023-12-06 257/week @ 2023-12-13 188/week @ 2023-12-20 179/week @ 2023-12-27 192/week @ 2024-01-03 227/week @ 2024-01-10 283/week @ 2024-01-17 239/week @ 2024-01-24 213/week @ 2024-01-31 268/week @ 2024-02-07 254/week @ 2024-02-14 246/week @ 2024-02-21 329/week @ 2024-02-28 288/week @ 2024-03-06 336/week @ 2024-03-13 242/week @ 2024-03-20

1,250 downloads per month
Used in 6 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