Crates.io | nest_struct |
lib.rs | nest_struct |
version | 0.5.2 |
source | src |
created_at | 2024-11-14 17:26:50.907623 |
updated_at | 2024-11-21 09:58:47.315287 |
description | Nest struct and enum definitions with minimal syntax changes |
homepage | |
repository | https://github.com/ZibanPirate/nest_struct |
max_upload_size | |
id | 1448123 |
size | 59,067 |
Nest struct and enum definitions with minimal syntax changes in Rust
use nest_struct::nest_struct;
#[nest_struct]
struct Post {
title: String,
summary: String,
author: nest! {
name: String,
handle: String,
},
}
struct Post {
title: String,
summary: String,
author: PostAuthor,
}
struct PostAuthor {
name: String,
handle: String,
}
You can also overwrite inner struct name, by passing the name itself as macro instead of nest!
:
use nest_struct::nest_struct;
#[nest_struct]
struct Post {
title: String,
summary: String,
author: Author! {
name: String,
handle: String,
},
}
struct Post {
title: String,
summary: String,
author: Author,
}
struct Author {
name: String,
handle: String,
}
Or, you can open a block and define struct like normal Rust code for full flexibility:
use nest_struct::nest_struct;
#[nest_struct]
struct Post {
title: String,
summary: String,
author: nest! {
/// doc comment for Author struct
#[derive(Debug)]
struct Author {
name: String,
handle: String,
}
},
}
struct Post {
title: String,
summary: String,
author: Author,
}
/// doc comment for Author struct
#[derive(Debug)]
struct Author {
name: String,
handle: String,
}
use nest_struct::nest_struct;
// Define a struct with nested struct definitions all in one place
// with minimal syntax changes.
#[nest_struct]
#[derive(serde::Deserialize)]
struct APIResponse {
id: u32,
name: String,
abilities: Vec<nest! {
ability: nest! { name: String, url: String },
is_hidden: bool,
slot: u32,
},
>,
}
let body = reqwest::blocking::get("https://pokeapi.co/api/v2/pokemon/ditto").unwrap().text().unwrap();
let api_response: APIResponse = serde_json::from_str(&body).unwrap();
assert_eq!(api_response.name, "ditto");
// Access nested struct fields
assert_eq!(api_response.abilities.first().unwrap().ability.name, "limber");
For more examples, see the ./tests/cases
directory.
struct
inside another struct
.enum
inside another enum
.enum
inside a struct
and vice-versa.derive
and other attribute macros from root struct
.struct
names.Feature parity with native Rust code:
impl
block on inner struct
s.derive
and other attribute macros individually per inner struct
.struct
.Contributions are welcome, please read CONTRIBUTING.md
to get started.
Licensed under MIT (twitter: @zibanpirate).