non-exhaustive

Crates.ionon-exhaustive
lib.rsnon-exhaustive
version0.1.1
sourcesrc
created_at2024-02-24 14:42:31.524914
updated_at2024-02-25 23:10:10.180024
descriptionmacro to allow struct expressions of non_exhaustive structs
homepage
repositoryhttps://github.com/ModProg/non-exhaustive
max_upload_size
id1151683
size24,146
Roland Fredenhagen (ModProg)

documentation

https://docs.rs/non-exhaustive

README

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
};
Commit count: 0

cargo fmt