[axum] Using trait's associated type in Path extractor

⚓ Rust    📅 2025-10-18    👤 surdeus    👁️ 2      

surdeus

I am trying to create a trait that provides a Router for types that implement another trate:

use crate::app::App;
use axum::{Router, Extension, extract::{Path, Json}, http::StatusCode, routing::*};

pub trait Api {
	const PATH: &str;

	type Id;

	async fn api_get(app: App, id: Self::Id) -> (StatusCode, String);
	/* ... */
}

trait ApiRouter: Api {
	fn api_router() -> Router;
}

impl<T: Api> ApiRouter for T {
	fn api_router() -> Router {
		let path_id = format!("{}/{{id}}", Self::PATH);
		Router::new()
			.route(&path_id, get(
				|state: Extension<App>, Path(id): Path<Self::Id>| async {
					(StatusCode::IM_A_TEAPOT, String::from("wat"))
				}
			))
			/* ... */
	}
}

I'm getting the typical the trait bound `{closure@...}: Handler<_, _>` is not satisfied which seems to be caused by the use of the associated type in Api

2 posts - 1 participant

Read full topic

🏷️ Rust_feed