#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

#2228 in Rust patterns

Download history 336/week @ 2024-03-13 255/week @ 2024-03-20 207/week @ 2024-03-27 336/week @ 2024-04-03 260/week @ 2024-04-10 235/week @ 2024-04-17 381/week @ 2024-04-24 372/week @ 2024-05-01 222/week @ 2024-05-08 243/week @ 2024-05-15 287/week @ 2024-05-22 217/week @ 2024-05-29 242/week @ 2024-06-05 181/week @ 2024-06-12 148/week @ 2024-06-19 227/week @ 2024-06-26

842 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