# xtruct
[](https://crates.io/crates/xtruct)
[](https://docs.rs/xtruct)
[](https://opensource.org/licenses/MIT)
An anonymous struct literal macro for Rust. `xtruct` allows you to construct lightweight, ad-hoc struct types on the fly without declaring explicit `struct` types beforehand.
## Features
- **Zero boilerplate:** Create anonymous structs inline with simple key-value syntax.
- **Field shorthand:** Infer fields directly from local variables in scope (e.g., `xtruct! { name, count }`).
- **Type inference:** Automatically infers field types based on the passed expressions.
## Usage Examples
### Construction
```rust
use xtruct::xtruct;
let user = xtruct! {
id: 1,
is_admin: true,
avatar_url: Some("https://example.com/avatar.png"),
};
assert_eq!(user.id, 1);
assert_eq!(user.is_admin, true);
assert_eq!(user.avatar_url, Some("https://example.com/avatar.png"));
```
### Variable Field Shorthand
Like standard Rust struct initialization, you can use local variables directly without repeating the field name:
```rust
use xtruct::xtruct;
let retry_count = 4usize;
let options = xtruct! {
timeout_ms: 2000,
retry_count,
};
assert_eq!(options.timeout_ms, 2000);
assert_eq!(options.retry_count, 4);
```
### Scoped Anonymous Structs
Construct anonymous structs inline within local scopes or expressions:
```rust
use xtruct::xtruct;
let payload = {
let status_code = 200;
let ok = true;
xtruct! { status_code, ok }
};
assert_eq!(payload.status_code, 200);
assert_eq!(payload.ok, true);
```
### Combining Expressions and Local Variables
Mix complex expressions and local variable shorthands in a single struct initialization:
```rust
use xtruct::xtruct;
let user_id = 101;
let is_active = true;
let session = xtruct! {
user_id,
auth_token: format!("token_{}", user_id),
is_active,
ttl_seconds: 3600,
};
assert_eq!(session.user_id, 101);
assert_eq!(session.auth_token, "token_101");
```
### Nested Anonymous Structs
Instantiate nested anonymous structures by nesting `xtruct!` invocations:
```rust
use xtruct::xtruct;
let config = xtruct! {
environment: "production",
database: xtruct! {
host: "localhost",
port: 5432,
},
};
assert_eq!(config.database.host, "localhost");
assert_eq!(config.database.port, 5432);
```
## Installation
Add `xtruct` to your `Cargo.toml`:
```toml
[dependencies]
xtruct = "0.1.0"
```
Or run:
```bash
cargo add xtruct
```
## License
This project is licensed under the [MIT License](LICENSE).