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.3.0"
🎯 Quick Start
use TypeStateBuilder;
// Enable ergonomic conversions for all setters
🛠️ Features
✨ Compile-Time Safety
The type-state pattern ensures that:
- Required fields must be set before calling
build() - Missing required fields cause friendly compile-time errors
- Missing optional fields default to their
Defaulttrait values or to the user-defined defaults - Ergonomic API with
impl Into<T>for setters, allowing you to pass&str,&[T], etc. directly - Custom conversion logic with
converterfor advanced transformations for setters - 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)]:
use TypeStateBuilder;
// 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:
use TypeStateBuilder;
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;
use TypeStateBuilder;
let doc = builder
.title
.content
// id and created_at are auto-generated, no setters available
.build;
🏷️ Custom Setter Names
Customize individual setter method names:
use TypeStateBuilder;
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:
use TypeStateBuilder;
let config = builder
.with_host
.with_port
.with_ssl_enabled
.build;
Field-Level Prefix Override
Field-level prefixes take precedence over struct-level prefixes:
use TypeStateBuilder;
let client = builder
.with_base_url
.set_api_key // Field-level prefix wins
.with_timeout
.build;
🔄 Ergonomic Conversions
The impl_into attribute generates setter methods that accept impl Into<FieldType> parameters, allowing for more
ergonomic API usage by automatically converting compatible types.
Struct-Level impl_into
Apply impl_into to all setters in the struct:
use TypeStateBuilder;
// Can now use &str directly instead of String::from() or .to_string()
let client = builder
.base_url // &str -> String
.api_key // &str -> String
.timeout
.user_agent // &str -> String
.build;
Field-Level Control with Precedence Rules
Field-level impl_into settings override struct-level defaults:
use TypeStateBuilder;
// Default for all fields
let doc = builder
.title // &str -> String (inherited)
.content // Must use String (override)
.category // impl Into for Option<String>
.tags // Must use Vec<String> (override)
.build;
Key Benefits:
- ✅ More ergonomic: Use
"string"instead of"string".to_string() - ✅ Flexible control: Apply globally or selectively
- ✅ Type safety: Maintains compile-time guarantees while improving ergonomics
- ✅ Zero cost: Conversions happen at compile time
Important Note: impl_into is incompatible with skip_setter since skipped fields don't have setter methods
generated.
🔧 Custom Conversions with converter
The converter attribute provides powerful custom transformation logic for field setters, enabling more advanced
conversions than impl_into can provide. Unlike impl_into which relies on the Into trait, converter allows you to
specify arbitrary transformation logic using closure expressions.
Improved Ergonomics for Option Fields
One of the most useful converter applications is improving ergonomics for Option<T> fields:
use TypeStateBuilder;
let profile = builder
.username
.bio // Verbose without converter
.display_name // Clean with converter!
.location // Clean with converter!
.build;
assert_eq!;
assert_eq!;
Basic Converter Usage
Use closure syntax to define custom conversion logic with explicit parameter types:
use TypeStateBuilder;
let user = builder
.name
.email // Will be normalized to "alice@example.com"
.interests // Parsed to Vec<String>
.age // Parsed from string to u32
.build;
assert_eq!;
assert_eq!;
assert_eq!;
Advanced Converter Examples
Converters support complex transformation logic:
use HashMap;
use TypeStateBuilder;
let config = builder
.debug_enabled
.env_vars
.allowed_hosts
.build;
assert_eq!;
assert_eq!;
assert_eq!;
Converter vs impl_into Comparison
| Feature | impl_into |
converter |
|---|---|---|
| Type conversions | Only Into trait |
Any custom logic |
| Parsing strings | ❌ Limited | ✅ Full support |
| Data validation | ❌ No | ✅ Custom validation |
| Complex transformations | ❌ No | ✅ Full support |
| Multiple input formats | ❌ Into only | ✅ Any input type |
| Performance | Zero-cost | Depends on logic |
| Syntax | Attribute flag | Closure expression |
When to Use converter
Use converter when:
- ✅ Improving Option ergonomics:
|value: &str| Some(value.to_string())instead ofSome(value.to_string()) - ✅ Parsing structured data from strings
- ✅ Normalizing or validating input data
- ✅ Complex data transformations
- ✅ Converting between incompatible types
- ✅ Custom business logic in setters
Use impl_into when:
- ✅ Simple type conversions (String/&str, PathBuf/&Path)
- ✅ The Into trait already provides the conversion you need
- ✅ You want zero-cost abstractions
Converter Syntax and Benefits
Important: The converter attribute requires closure expressions, not function references:
// ✅ Correct - inline closure expression
tags: ,
// ❌ Incorrect - cannot reference external functions
// #[builder(converter = some_function)] // This doesn't work!
Why closure expressions?
The closure syntax provides several benefits:
- ✅ IDE Support: Full autocomplete, syntax highlighting, and type checking
- ✅ Type Inference: Parameter types are explicitly declared and validated
- ✅ Compile-Time Validation: Syntax errors caught immediately
- ✅ Refactoring Safety: Changes are tracked by your IDE and compiler
- ✅ Documentation: The conversion logic is visible at the field definition
Important Notes
- Default values must be passed as string literals:
#[builder(default = "Vec::new()")] - Converter expressions use closure syntax:
#[builder(converter = |param: Type| expression)] converteris incompatible withskip_setterandimpl_into(different approaches to setter generation)- The closure parameter type must be explicitly specified for proper code generation
🏗️ Custom Build Method
Customize the name of the build method:
use TypeStateBuilder;
let user = builder
.name
.create; // Custom build method name
🧬 Generics Support
TypeStateBuilder works seamlessly with generic types, lifetimes, and complex bounds:
use TypeStateBuilder;
let container = builder
.primary
.secondary
.metadata
.build;
Lifetime Support
use TypeStateBuilder;
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:
use TypeStateBuilder;
Field-Level Attributes
Applied to individual fields:
use TypeStateBuilder;
Attribute Combinations
Some attributes work together, others are mutually exclusive:
use TypeStateBuilder;
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)]
Incompatible Conversions:
// ❌ Error!
field: String,
Error message:
error: Field-level impl_into is incompatible with skip_setter. Remove one of these attributes.
🎨 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:
use TypeStateBuilder;
// 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:
use TypeStateBuilder;
// 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;
Configuration Builder with Ergonomic Conversions
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:
use TypeStateBuilder;
Q: What if I need to set fields conditionally?
A: Use optional fields and set them based on conditions:
use TypeStateBuilder;
let is_debug = true;
let mut builder = builder
.mode;
if is_debug
let config = builder.build;
Q: What's the difference between regular setters, impl_into, and converter?
A: Each provides different levels of flexibility and functionality:
use TypeStateBuilder;
let example = builder
.name // Regular: must use String
.title // impl_into: can use &str via Into
.email // converter: custom normalization
.build;
assert_eq!; // Normalized!
Comparison:
| Feature | Regular | impl_into |
converter |
|---|---|---|---|
| Type flexibility | Exact match | Into trait | Any input type |
| Custom logic | ❌ No | ❌ No | ✅ Full support |
| Performance | Zero-cost | Zero-cost | Depends on logic |
| Syntax | Simple | Attribute flag | Closure expression |
When to use each:
- Regular: When you want exact type control
impl_into: For simple ergonomic conversions (String/&str, PathBuf/&Path)converter: For parsing, validation, normalization, or complex transformations
🔧 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:
use TypeStateBuilder;
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! 🚀