2 releases
Uses new Rust 2024
| 0.1.1 | Sep 8, 2025 |
|---|---|
| 0.1.0 | Sep 8, 2025 |
#1539 in Rust patterns
28KB
585 lines
Nesting
Nesting is a Rust proc-macro library for defining structs, enums, and impls in a nested fashion.
Ideal for writing configs or heavily-nested data structures.
Installation
$ cargo add nesting
Example
nesting::nest! {
#![derive(Debug)]
struct MyStruct {
child: MyChildStruct
struct MyChildStruct {
is_nested: bool,
impl Default for MyChildStruct {
fn default() -> Self {
Self { is_nested: true}
}
}
}
}
}
fn main() {
let x = MyStruct {
child: MyChildStruct::default(),
};
dbg!(&x);
}
Check out the docs for more info or take a look at the nesting-examples directory for a more detailed showcase of everything you can do with this crate.
lib.rs:
Nested Structs & Enums
This crate allows you to nest structs, enums, and impls, in a way that is similar to how it's done in Zig.
Examples
nesting::nest! {
// #![] attributes apply to all structs and enums in the nest!{} block.
#![derive(Debug)]
// Becomes:
// #![structs(allow(dead_code))]
// #![enums(allow(dead_code))]
// You can also scope the attributes like so:
#![all(allow(dead_code))] // using `all` means it will also apply to `impl`s!
// Which is the same as:
// #![structs(allow(dead_code))]
// #![enums(allow(dead_code))]
// #![impls(allow(dead_code))]
pub struct MarkerStruct;
struct TupleStruct(String, u32);
struct FieldStruct {
field1: String,
field2: u32
child: ChildStruct,
my_enum: Enum
// Loose functions get put into impl StructName {} blocks.
// i.e. this would be impl FieldStruct { pub fn my_fn() {} }
pub fn some_struct_fn(&self) {
println!("This function is nested inside the struct!");
}
// You can add attributes to individual structs/enums/impls as usual
#[derive(Clone, Hash)]
struct ChildStruct {
field1: String,
field2: u32,
child: ChildChildStruct
// You can nest infinitely...
#[derive(Clone, Hash)]
struct ChildChildStruct;
}
impl ChildStruct {
pub fn some_impl_fn(&self) {
println!("This function is nested inside struct->impl");
}
}
// We can impl Foo for Bar
impl std::fmt::Display for ChildStruct {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}", &self.field1, self.field2)
}
}
// We can make enums too
enum Enum {
A,
B(String),
C {
a: String,
b: u64,
}
// Nesting works just fine in enums
#[derive(Default)]
struct StructInsideEnum(String);
enum Enum2 { A, B, C }
pub fn some_enum_fn(&self) {
println!("This is a function inside an enum!");
}
}
}
}
Dependencies
~115–490KB
~12K SLoC