injectables
A Rust procedural macro library that enables field injection between structs through declarative attributes. This library allows you to compose structs by automatically injecting fields from one or more source structs while respecting Rust's visibility rules and ownership semantics.
Features
- 🔒 Respects Rust's visibility rules (
pub,pub(crate), private) - 🧬 Supports generic types with concrete type resolution
- ⚡ Compile-time dependency injection and validation
- 🔍 Detects circular dependencies and invalid injections at compile time
- 🌳 Supports nested/transitive injections
- 📦 Zero runtime overhead
Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
Basic Usage
use ;
// Mark source struct as injectable
// Inject fields from Base into Document
Advanced Features
Generic Type Support
The library handles generic types with concrete type specifications:
let container = Container ;
Nested Injections
Fields can be injected transitively through multiple structs:
// C will have fields: description, name (from B), and id (from A)
Visibility Rules
The library respects Rust's visibility rules:
// Can only inject visible fields based on module boundaries
Compile-Time Validations
The library performs several compile-time checks to ensure correct usage:
- ❌ Prevents circular dependencies between structs
- ❌ Detects duplicate field names
- ❌ Validates visibility access rules
- ❌ Ensures source structs are marked as
#[injectable] - ❌ Prevents injection into enums or non-struct types
- ❌ Validates generic type parameters
Current Limitations
- Only works with named struct fields (not tuple structs)
- Cannot inject fields into enums
- Source structs must be marked with
#[injectable]before being used ininject_fields - Injected fields maintain their original visibility rules
- When using generic types, concrete types must be specified in
inject_fields
Error Messages
The library provides clear compile-time error messages:
-
When attempting circular injections:
error: Circular injection chain detected: A already depends on B -
When accessing private fields from invalid module:
error: Cannot access private field 'id' from struct 'Private' defined in module 'other_module'
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
Licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.
Safety
This crate uses #![forbid(unsafe_code)] to ensure 100% safe Rust.