Trait bound is not satisfied when attempting to use with_state() #2713
-
SummaryHi. I get the following errors when running cargo check: error[E0277]: the trait bound error[E0277]: the trait bound For more information about this error, try I'm new to Axum so I apologise if the solution is obvious. Any help would be appreciated. Following is the source code: use axum::routing::get; #[tokio::main] #[allow(dead_code)] async fn show_state(axum::extract::State(shared_state): axum::extract::State) -> String { async fn fallback(uri: axum::http::Uri) -> impl axum::response::IntoResponse { async fn get_root() -> axum::response::Html<&'static str> { #[derive(Clone, Debug, Copy)] axum version0.7.5 |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Hi you need to remove the The final code is below: use axum::routing::get;
#[tokio::main]
async fn main() {
let shared_state: AppState = AppState { num: 42 };
let app = setup_routing(shared_state);
let listener = tokio::net::TcpListener::bind("localhost:5000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
#[allow(dead_code)]
fn setup_routing(shared_state: AppState) -> axum::Router {
axum::Router::new()
.fallback(fallback)
.nest_service("/static", tower_http::services::ServeDir::new("static"))
.route("/", get(get_root))
.route("/show-state", get(show_state))
.with_state(shared_state) // only adds state to all prior routes
}
async fn show_state(axum::extract::State(shared_state): axum::extract::State<AppState>) -> String {
format!("shared state = {shared_state:?}")
}
async fn fallback(uri: axum::http::Uri) -> impl axum::response::IntoResponse {
(axum::http::StatusCode::NOT_FOUND, format!("No route {uri}"))
}
async fn get_root() -> axum::response::Html<&'static str> {
include_str!("../static/root.html").into()
}
#[derive(Clone, Debug, Copy)]
#[allow(dead_code)]
pub struct AppState {
num: i32,
} |
Beta Was this translation helpful? Give feedback.
-
Hi. That worked! |
Beta Was this translation helpful? Give feedback.
Hi you need to remove the
turbo fish
(double colons) next to the.with_state
.And then you need to point the
axum::extract::State
's generic type thruaxum::extract::State<AppState>
.The final code is below: