TypeStateBuilder
TypeStateBuilder is a Rust derive macro that generates compile-time safe builders using the type-state builder pattern. It prevents runtime errors by making it impossible to build incomplete objects, while providing an ergonomic and intuitive API and developer-friendly compilation errors.
📚 Table of Contents
- 🚀 Why TypeStateBuilder?
- 📦 Installation
- 🎯 Quick Start
- 🛠️ Features
- 📋 Complete Attribute Reference
- 🎨 Builder Patterns
- 🔍 Examples
- ❓ FAQ
- 🔧 How It Works
- 🦀 Minimum Supported Rust Version
- 📄 License
- 🤝 Contributing
- 📬 Support
🚀 Why TypeStateBuilder?
Traditional builders can fail at runtime:
// ❌ This compiles but panics at runtime!
let user = builder
.name
// Forgot to set required email!
.build; // 💥 Panic (or runtime error if builder returns a `Result`)!
With TypeStateBuilder, this becomes a compile-time error:
// ✅ This won't even compile!
let user = builder
.name
// .email("alice@example.com") <- Compiler error: missing required field!
.build; // ❌ Compile error, not runtime panic!
📦 Installation
Add this to your Cargo.toml:
[]
= "0.1.0"
🎯 Quick Start
use TypeStateBuilder;
🛠️ Features
✨ Compile-Time Safety
The type-state pattern ensures that:
- Required fields must be set before calling
build() - Missing required fields cause compile-time errors
- Missing optional fields default to their
Defaulttrait values or to the user-defined defaults - No runtime panics due to incomplete builders
- IDE support with accurate autocomplete and error messages
🎛️ Field Types
Required Fields
Mark fields as required with #[builder(required)]:
// Must set both api_key and endpoint
let config = builder
.api_key
.endpoint
.timeout
.build;
Optional Fields with Custom Defaults
Provide custom default values for optional fields:
let config = builder
.host
// port defaults to 5432
// max_connections defaults to 10
// database_name defaults to "postgres"
.build;
Skip Setter Fields
Some fields should only use their default value and not have setters:
use Uuid;
let doc = builder
.title
.content
// id and created_at are auto-generated, no setters available
.build;
🏷️ Custom Setter Names
Customize individual setter method names:
let person = builder
.full_name
.years_old
.build;
🎯 Setter Prefixes
Add consistent prefixes to all setter methods:
Struct-Level Prefix
Apply a prefix to all setters in the struct:
let config = builder
.with_host
.with_port
.with_ssl_enabled
.build;
Field-Level Prefix Override
Field-level prefixes take precedence over struct-level prefixes:
let client = builder
.with_base_url
.set_api_key // Field-level prefix wins
.with_timeout
.build;
🏗️ Custom Build Method
Customize the name of the build method:
let user = builder
.name
.create; // Custom build method name
🧬 Generics Support
TypeStateBuilder works seamlessly with generic types, lifetimes, and complex bounds:
let container = builder
.primary
.secondary
.metadata
.build;
Lifetime Support
let title = "My Document";
let content = "Hello, world!";
let doc = builder
.title
.content
.tags
.build;
💬 Developer-Friendly Error Messages
TypeStateBuilder generates descriptive type names that make compiler errors immediately actionable. Instead of cryptic type names, you get clear guidance about what's missing:
Missing Required Fields
let user = builder
.name
.build; // ❌ Trying to build without setting email
Error message:
error[E0599]: no method named `build` found for struct `UserBuilder_HasName_MissingEmail`
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Clear indication: name is set ✅, email is missing ❌
Multiple Missing Fields
let config = builder
.build; // ❌ Missing both required fields
Error message:
error[E0599]: no method named `build` found for struct `ServerConfigBuilder_MissingHost_MissingPort`
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Shows exactly what needs to be set: host and port
These descriptive error messages help you:
- ✅ See progress made:
HasNameshows what's already set - ✅ Identify missing fields:
MissingEmailshows what's needed - ✅ Get immediate guidance: No guessing what went wrong
- ✅ IDE support: Meaningful autocomplete and hover information
📋 Complete Attribute Reference
Struct-Level Attributes
Applied to the struct itself:
Field-Level Attributes
Applied to individual fields:
Attribute Combinations
Some attributes work together, others are mutually exclusive:
Compilation Error Examples
Duplicate Attributes:
// ❌ Error!
name: String,
Error message:
error: Duplicate setter_name attribute. Only one setter_name is allowed per field
Conflicting Logic:
// ❌ Error!
name: String,
Error message:
error: Required fields cannot have default values. Remove #[builder(default = "...")]
or make the field optional by removing #[builder(required)]
🎨 Builder Patterns
TypeStateBuilder automatically chooses the best builder pattern based on your struct:
Type-State Builder (Recommended)
Used when your struct has required fields. Provides compile-time safety:
// Compile-time enforced order - must set required fields first
let user = builder // Initial state: neither field set
.name // Transition: name is now set
.email // Transition: both fields set
.age // Optional fields can be set anytime
.build; // ✅ Now build() is available
Regular Builder
Used when your struct has only optional fields. Immediate build() availability:
// build() is available immediately since all fields are optional
let config = builder
.timeout
.build; // ✅ Can build anytime
🔍 Examples
Web API Configuration
use TypeStateBuilder;
Database Connection
use TypeStateBuilder;
Generic Data Container
use TypeStateBuilder;
use HashMap;
❓ FAQ
Q: When should I use TypeStateBuilder vs other builder libraries?
A: Use TypeStateBuilder when:
- ✅ You have required fields that must be set
- ✅ You want compile-time safety instead of runtime panics
- ✅ You're building configuration objects, API clients, or data structures
- ✅ You want zero runtime overhead
Q: Does TypeStateBuilder work with existing Rust features?
A: Yes! TypeStateBuilder works with:
- ✅ Generic types and lifetime parameters
- ✅ Complex where clauses and trait bounds
- ✅ Derive macros like
Debug,Clone,PartialEq - ✅ Serde serialization/deserialization
- ✅ Custom implementations and methods
Q: What's the performance impact?
A: Zero! TypeStateBuilder:
- ✅ Has zero runtime overhead - it's all compile-time
- ✅ Generates efficient code equivalent to manual builders
- ✅ Uses Rust's zero-cost abstractions
- ✅ The type-state transitions are compile-time only
Q: Can I mix required and optional fields?
A: Absolutely! That's the main use case:
Q: What if I need to set fields conditionally?
A: Use optional fields and set them based on conditions:
let is_debug = true;
let mut builder = builder
.mode;
if is_debug
let config = builder.build;
🔧 How It Works
TypeStateBuilder uses Rust's powerful type system to create a compile-time state machine. Here's the magic:
The Type-State Pattern
When you have required fields, TypeStateBuilder generates multiple builder types representing different states. Consider this example struct:
For this struct with 2 required fields, TypeStateBuilder generates states like:
// Different builder states with descriptive type names:
// - UserBuilder_MissingName_MissingEmail: Neither field set
// - UserBuilder_HasName_MissingEmail: Name set, email missing
// - UserBuilder_MissingName_HasEmail: Email set, name missing
// - UserBuilder_HasName_HasEmail: Both fields set (can build!)
Setter Method Magic
Each setter method transitions between states:
Smart Builder Selection
TypeStateBuilder automatically chooses the right pattern:
- Type-State Builder: When you have required fields (compile-time safety)
- Regular Builder: When all fields are optional (immediate
build()availability)
Zero Runtime Cost
All the type-state magic happens at compile time:
- ✅ No runtime state tracking
- ✅ No runtime validation
- ✅ No performance overhead
- ✅ Generated code is as efficient as hand-written builders
The end result? You get the safety of compile-time validation with the performance of hand-optimized code!
🦀 Minimum Supported Rust Version
TypeStateBuilder supports Rust 1.70.0 and later.
The MSRV is checked in our CI and we will not bump it without a minor version release. We reserve the right to bump the MSRV in minor releases if required by dependencies or to enable significant improvements.
Why 1.70.0?
- Required for stable proc-macro features used in code generation
- Needed for advanced generic parameter handling
- Ensures compatibility with modern Rust ecosystem
📄 License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
📬 Support
If you have questions or need help, please:
- 📖 Check the documentation
- 🐛 Open an issue for bugs
- 💡 Start a discussion for questions
Happy Building! 🚀