#options #chain #macro #no-std

no-std option-chain

A macro for using ? operator in functions that don’t return Option

3 releases

Uses new Rust 2024

new 0.1.2 Mar 28, 2025
0.1.1 Mar 25, 2025
0.1.0 Mar 22, 2025

#349 in Procedural macros

Download history 185/week @ 2025-03-20

185 downloads per month

GPL-3.0-or-later

5KB
74 lines

Logo

option-chain

A macro for using ? operator in functions that don't return Option.

Examples

use option_chain::opt;

struct Test1 {
    a: Option<Test2>,
}
struct Test2 {
    b: Option<Test3>,
}
struct Test3 {
    c: i32,
}

let v = Test1 {
    a: Some(Test2 { b: Some(Test3 { c: 42 }) }),
};
let v = opt!(v.a?.b?.c);
assert_eq!(v.unwrap(), 42);

Implementation

It just wraps the expression in a closure that returns Option:

macro_rules! opt {
    ($e:expr) => {{ || -> Option<_> { Some($e) }() }};
}

No runtime deps