Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce unstruct macro to help destructuring #39

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,41 @@ macro_rules! imap_deconstruct {
};
}

/// A macro to help with destructuring structs by cloning its field.
///
/// This macro works very similarly to the built-in syntax for struct destructuring but it has 2
/// major quality-of-life improvements:
///
/// 1. The fields are cloned individually instead of cloning the whole struct.
/// 2. The type of the struct is not needed for destructuring.
///
/// ```rust
/// # use implicit_clone::unstruct;
/// # #[derive(Clone)]
/// # struct Struct { x: u32, y: u32 }
/// let s = Struct { x: 5, y: 6 };
///
/// // built-in struct destructuring
/// let Struct { x, y } = s.clone();
/// assert_eq!(x, 5);
/// assert_eq!(y, 6);
///
/// // unstruct
/// unstruct! {
/// let { x, y } = s;
/// }
/// assert_eq!(x, 5);
/// assert_eq!(y, 6);
/// ```
///
/// Renaming field is not supported by this macro.
#[macro_export]
macro_rules! unstruct {
(let { $($field:ident),* $(,)? } = $struct:expr;) => {
$(let $field = $crate::ImplicitClone::implicit_clone(&$struct.$field);)*
}
}

#[cfg(test)]
mod test {
use super::*;
Expand Down