Rust macro to use a match-like syntax as a elegant alternative to nesting if-else statement

Related tags

Miscellaneous cond
Overview

cond

Rust macro to use a match-like syntax as an elegant alternative to many if-else statements.

I got the idea from empty Go switch statements. I thought it could be cool if it was in Rust so I asked if that was possible in the Rust community Discord server. They told me it wasn't unless you used a pretty ugly syntax in a match, and Esper89 (GitHub in credits) made a macro for it. I added some tests and documentation and here's my first Rust crate.

Example

use cond::cond;

fn main() {
    let a = 195;
    cond! {
        a < 5 => println!("a is less than 5"),
        a == 195 => {
            println!("this is the way")
        },
        a > 10 => println!("a is greater than 10"),

        // The conditions are executed by order: if one condition is true, conditions below will not get evaluated
    };

    let b = "";
    let result = cond! { // Or use it as a block to return a value
        b == "something" => false,
        b.chars().count() > 10 => true,
        a < 10000 => true,
        _ => false // You must add a default with the return type if you want to return
    };

    println!("result: {}", result);
}

Usage

You can just add the crate with:

cargo add cond

Or just add the 8 line macro to your project:

macro_rules! cond {
    ($($condition:expr => $value:expr),* $(, _ => $default:expr)? $(,)?) => {
        match () {
            $(() if $condition => $value,)*
            () => ($($default)?),
        }
    };
}

Credits

Credits to Esper89 for essentially making the whole macro in the Rust community Discord server.

You might also like...
馃悁 Building a federated alternative to reddit in rust

Lemmy A link aggregator / Reddit clone for the fediverse. Join Lemmy 路 Documentation 路 Report Bug 路 Request Feature 路 Releases 路 Code of Conduct About

Swayidle alternative to handle wayland idle notifications, sleep and lock events in Rust with Lua scripting based configuration language

swayidle-rs This is intended as a replacement of sway's idle management daemon. I use it as a tool to understand rust message passing and state manage

A stupid macro that compiles and executes Rust and spits the output directly into your Rust code

inline-rust This is a stupid macro inspired by inline-python that compiles and executes Rust and spits the output directly into your Rust code. There

 Libreddit - An alternative private front-end to Reddit
Libreddit - An alternative private front-end to Reddit

Libreddit - An alternative private front-end to Reddit

Blueboat is an open-source alternative to Cloudflare Workers. The monolithic engine for serverless web apps.

Blueboat Blueboat is an open-source alternative to Cloudflare Workers. Blueboat aims to be a developer-friendly, multi-tenant platform for serverless

Alternative basic focus movement for the sway and i3 window managers.
Alternative basic focus movement for the sway and i3 window managers.

sway-overfocus Alternative basic focus movement for the sway and i3 window managers. The primary goal of this program is to create one set of keybinds

Polydrive an experimental open source alternative to Google Drive

Polydrive is an experimental open source alternative to Google Drive. It allows users to synchronize their files on multiple devices.

A Rust proc-macro crate which derives functions to compile and parse back enums and structs to and from a bytecode representation

Bytecode A simple way to derive bytecode for you Enums and Structs. What is this This is a crate that provides a proc macro which will derive bytecode

This crate provides a convenient macro that allows you to generate type wrappers that promise to always uphold arbitrary invariants that you specified.

prae This crate provides a convenient macro that allows you to generate type wrappers that promise to always uphold arbitrary invariants that you spec

Comments
  • Rename metavariables and improve documentation.

    Rename metavariables and improve documentation.

    Renames the $cond and $dft metavariables to $condition and $default, for clarity. Also improves documentation, fixes the broken doc test, and fixes a couple grammar and markdown mistakes in README.

    opened by Esper89 1
Owner
CheckM4te
I like music and coding. Rust is great.
CheckM4te
Ointers is a library for representing pointers where some bits have been stolen so that they may be used by the programmer for something else

Ointers is a library for representing pointers where some bits have been stolen so that they may be used by the programmer for something else. In effect, it's a small amount of free storage

Irrustible 8 Jun 4, 2022
Elegant, clean Rust development framework

Preview version, will not guarantee the stability of the API! Elegant, clean Rust development framework Core Features Relational database client for M

Ideal World 35 Dec 29, 2022
A tool that, like, screams at you when you say like

Dislike Do you, like,... dislike constantly saying "like" as much as I do? Then, like,... you've come the right place! This tool is like EXACTLY what

ElKowar 27 Jun 27, 2022
`Debug` in rust, but only supports valid rust syntax and outputs nicely formatted using pretty-please

dbg-pls A Debug-like trait for rust that outputs properly formatted code Showcase Take the following code: let code = r#" [ "Hello, World!

Conrad Ludgate 12 Dec 22, 2022
a simple compiled language i made in rust. it uses intermediate representation (IR) instead of an abstract syntax tree (AST).

a simple compiled language i made in rust. it uses intermediate representation (IR) instead of an abstract syntax tree (AST).

null 4 Oct 3, 2022
Analogous, indented syntax for the Rust programming language.

Note: After experimenting with this in the wild, I have found representing keywords as symbols to be far less readable in large codebases. Additionall

null 42 Oct 2, 2021
A syntax exploration of eventually stable Rust Iterator items

Rust Iterator Items: a syntax exploration This crate is a thin wrapper around the unstable generator feature, allowing users to create new items that

Esteban Kuber 28 Sep 1, 2022
This crate converts Rust compatible regex-syntax to Vim's NFA engine compatible regex.

This crate converts Rust compatible regex-syntax to Vim's NFA engine compatible regex.

kaiuri 1 Feb 11, 2022
tr-lang is a language that aims to bring programming language syntax closer to Turkish.

tr-lang Made with 鉂わ笍 in ???? tr-lang is a language that aims to bring programming language syntax closer to Turkish. tr-lang is a stack based language

Kerem G枚ksu 10 Apr 2, 2022
`grep` but with PEG patterns. Define grammars (e.g. `digit`), functions for matching. No more regex syntax!

PEG peggrep Example file demo_file: THIS LINE IS THE 1ST UPPER CASE LINE IN THIS FILE. this line is the 1st lower case line in this file. This Line Ha

IchHabeKeineNamen 3 Apr 18, 2023