1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//! ⚠️ This crate is **deprecated**. Use the [`let-else`](https://doc.rust-lang.org/rust-by-example/flow_control/let_else.html) statement instead.
//!
//! The `let-else` statement is exactly doing what I intended to do with `let_or_return` macro:
//!
//! ```
//! fn process_x(opt_x: &Option<u32>) -> bool {
//! let Some(x) = opt_x else { return false };
//! // use x
//! true
//! }
//! ```
//!
//! ---
//! Original documentation
//!
//! Convenient macro to extract a value via `if let`, and `return` in the else case.
/// Extract a value via `if let`, and `return` in the else case.
///
/// The macro is a convenient and concise way to extract value(s)
/// using a pattern, and return if the pattern does not match.
///
/// It avoids the cumulated indentation and reduces the boiler plate
/// of `if let ... {...} else { return ... }` statements.
///
/// # Description
///
/// Signature: let_or_return!(pattern [=> var] [, ret])
/// - pattern is the pattern for variable(s) extraction
/// - var is the extracted variable(s) (optional for a simple pattern)
/// - ret is the return value when the pattern does not match (optional)
///
/// # Examples
/// ## Simple pattern
/// ```
/// use let_or_return::let_or_return;
///
/// fn process_x(opt_x: &Option<u32>) -> bool {
/// let_or_return!(Some(x) = opt_x, false);
/// // use x
/// true
/// }
/// ```
/// will expand to
/// ```
/// fn process_x(opt_x: &Option<u32>) -> bool {
/// let x = if let Some(x) = opt_x { x } else { return false };
/// // use x
/// true
/// }
/// ```
///
/// ## Complex pattern, with explicit variable parameter
/// ```
/// use let_or_return::let_or_return;
///
/// struct A {
/// a: Option<u32>,
/// b: u32,
/// }
///
/// fn process_x(in_x: &A) -> bool {
/// let_or_return!(A { a: Some(a), b } = in_x => (a, b), false);
/// // use a and b
/// true
/// }
/// ```
/// will expand to
/// ```
/// struct A {
/// a: Option<u32>,
/// b: u32,
/// }
///
/// fn process_x(in_x: &A) -> bool {
/// let (a, b) = if let A { a: Some(a), b } = in_x {
/// (a, b)
/// } else {
/// return false;
/// };
/// // use a and b
/// true
/// }
/// ```
else ;
};
// complex pattern: pattern = input => var [, ret]
=> ;
}