#structs #struct #macro #no-alloc

no-std non-exhaustive

macro to allow struct expressions of non_exhaustive structs

2 releases

0.1.1 Feb 25, 2024
0.1.0 Feb 24, 2024

#863 in Development tools

Download history 86/week @ 2024-02-18 266/week @ 2024-02-25 9/week @ 2024-03-03 23/week @ 2024-03-10 42/week @ 2024-03-17 29/week @ 2024-03-24 80/week @ 2024-03-31 36/week @ 2024-04-07 25/week @ 2024-04-14

178 downloads per month

MIT/Apache

9KB

non-exhaustive

CI Status Crates.io Docs.rs Documentation for main

Macro to create non_exhaustive structs and structs with private fields with the functional update syntax, i.e., using ..Default::default().

Given the foreign structs:

#[non_exhaustive]
#[derive(Default)]
pub struct NonExhaustive {
  pub field: usize
}

#[derive(Default)]
pub struct PrivateFields {
  pub pub_field: usize,
  private_field: usize
}

The following is not possible:

NonExhaustive {
  field: 1,
  ..Default::default()
};

PrivateFields {
  pub_field: 1,
  ..Default::default()
};

non_exhaustive! remedies that:

use non_exhaustive::non_exhaustive;
# mod module {#[derive(Default)] pub struct NonExhaustive {pub field: usize, _hack: usize} #[derive(Default)] pub struct PrivateFields { pub pub_field: usize, private_field: usize}} use module::*;

non_exhaustive! {NonExhaustive {
  field: 1,
  ..Default::default()
}};

non_exhaustive! {PrivateFields {
  pub_field: 1,
  ..Default::default()
}};

For the common case of using Default::default(), non_exhaustive! allows omitting the ..expression:

use non_exhaustive::non_exhaustive;
# mod module {#[derive(Default)] pub struct NonExhaustive {pub field: usize, _hack: usize} #[derive(Default)] pub struct PrivateFields { pub pub_field: usize, private_field: usize}} use module::*;

non_exhaustive!(NonExhaustive { field: 1 });
non_exhaustive!(PrivateFields { pub_field: 1 });

Under the hood, non_exhaustive! is extremely simple, it expands to:

# mod module {#[derive(Default)] pub struct NonExhaustive {pub field: usize, _hack: usize}} use module::*;

{
  let mut value: NonExhaustive = Default::default();
  value.field = 1;
  value
};

No runtime deps