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.
- 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.
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"));Like standard Rust struct initialization, you can use local variables directly without repeating the field name:
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);Construct anonymous structs inline within local scopes or expressions:
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);Mix complex expressions and local variable shorthands in a single struct initialization:
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");Instantiate nested anonymous structures by nesting xtruct! invocations:
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);Add xtruct to your Cargo.toml:
[dependencies]
xtruct = "0.1.0"Or run:
cargo add xtructThis project is licensed under the MIT License.