Skip to content

Commit

Permalink
State always needs to implement Clone
Browse files Browse the repository at this point in the history
Fix #2821
  • Loading branch information
yanns committed Oct 10, 2024
1 parent 9feb526 commit 576b976
Showing 1 changed file with 3 additions and 29 deletions.
32 changes: 3 additions & 29 deletions axum/src/extract/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use std::{
/// // here you can put configuration, database connection pools, or whatever
/// // state you need
/// //
/// // see "When states need to implement `Clone`" for more details on why we need
/// // see "Why states need to implement `Clone`" for more details on why we need
/// // `#[derive(Clone)]` here.
/// #[derive(Clone)]
/// struct AppState {}
Expand Down Expand Up @@ -247,14 +247,14 @@ use std::{
/// }
/// ```
///
/// # When states need to implement `Clone`
/// # Why states need to implement `Clone`
///
/// Your top level state type must implement `Clone` to be extractable with `State`:
///
/// ```
/// use axum::extract::State;
///
/// // no substates, so to extract to `State<AppState>` we must implement `Clone` for `AppState`
/// // to extract to `State<AppState>` we must implement `Clone` for `AppState`
/// #[derive(Clone)]
/// struct AppState {}
///
Expand All @@ -265,32 +265,6 @@ use std::{
///
/// This works because of [`impl<S> FromRef<S> for S where S: Clone`][`FromRef`].
///
/// This is also true if you're extracting substates, unless you _never_ extract the top level
/// state itself:
///
/// ```
/// use axum::extract::{State, FromRef};
///
/// // we never extract `State<AppState>`, just `State<InnerState>`. So `AppState` doesn't need to
/// // implement `Clone`
/// struct AppState {
/// inner: InnerState,
/// }
///
/// #[derive(Clone)]
/// struct InnerState {}
///
/// impl FromRef<AppState> for InnerState {
/// fn from_ref(app_state: &AppState) -> InnerState {
/// app_state.inner.clone()
/// }
/// }
///
/// async fn api_users(State(inner): State<InnerState>) {
/// // ...
/// }
/// ```
///
/// In general however we recommend you implement `Clone` for all your state types to avoid
/// potential type errors.
///
Expand Down

0 comments on commit 576b976

Please sign in to comment.