Last active
January 29, 2023 14:43
-
-
Save yuryshulaev/2ca32aee1a0f4bf808bafb93f3ec500f to your computer and use it in GitHub Desktop.
Rust macro to conveniently bind temporary value in a chain to a temporary variable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// error[E0716]: temporary value dropped while borrowed | |
// --> src/main.rs:21:14 | |
// | | |
// 21 | let upper = "abc".to_uppercase().as_str(); | |
// | ^^^^^^^^^^^^^^^^^^^^ - temporary value is freed at the end of this statement | |
// | | | |
// | creates a temporary which is freed while still in use | |
// 22 | println!("{}", upper); | |
// | ----- borrow later used here | |
// | | |
// help: consider using a `let` binding to create a longer lived value | |
// | | |
// 21 ~ let binding = "abc".to_uppercase(); | |
// 22 ~ let upper = binding.as_str(); | |
// | | |
// | |
// For more information about this error, try `rustc --explain E0716`. | |
/// Allows you to write this: | |
/// ``` | |
/// let_chain!(upper = ("abc".to_uppercase()).as_str()); | |
/// ``` | |
/// instead of | |
/// ``` | |
/// let binding = "abc".to_uppercase(); | |
/// let upper = binding.as_str(); | |
/// ``` | |
#[macro_export] | |
macro_rules! let_chain { | |
($name:ident = ($expr:expr)$($chain:tt)*) => ( | |
let binding = $expr; | |
let $name = binding$($chain)*; | |
); | |
(mut $name:ident = ($expr:expr)$($chain:tt)*) => ( | |
let binding = $expr; | |
let mut $name = binding$($chain)*; | |
); | |
($name:ident = (mut $expr:expr)$($chain:tt)*) => ( | |
let mut binding = $expr; | |
let $name = binding$($chain)*; | |
); | |
(mut $name:ident = (mut $expr:expr)$($chain:tt)*) => ( | |
let mut binding = $expr; | |
let mut $name = binding$($chain)*; | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment