Type signature
Basic usage
With Router
State must implement
Clone since it’s cloned for each request. Use Arc for expensive-to-clone types.With MethodRouter
With Handler
Extractor ordering
Combining routers
When combining routers withRouter::nest or Router::merge, they must have the same state type:
Explicit state types
When composing routers in separate functions, you may need to annotate the state type:Substates
You can extract “substates” usingFromRef to provide different state to different parts of your app:
FromRef:
Shared mutable state
Since state is cloned for each request, you can’t directly get a mutable reference. UseArc<Mutex<_>> or similar:
State vs Extension
For global application state shared across all requests, preferState because:
- Type-safe: The state type is part of the router’s type
- Compile-time checked: Wrong state types are caught at compile time
- Better error messages
Extension for request-derived data like authorization info or per-request context.