Rocket | 04 , Dynamic Paths
We can declare dynamic path segments in route’s path by using angle brackets around variable names
use rocket::{ get, routes};
#[rocket::main]
async fn main() {
rocket::build().mount("/", routes![index]).launch().await.unwrap();
}
#[get("/user/<id>")]
fn index(id: i32) -> String {
format!("id: {}", id)
}
In index handler , we give it path start with /user/ , after the first segment , is dynamic path segment , id is variable name , we put id in a pair of angle brackets
Get Mike Code’s stories in your inbox
Join Medium for free to get updates from this writer.
Then in handler , we add a parameter with type annotation. And parameter’s name must be the same as variable’s name in the dynamic path segment .
Last we mount this handler to rocket server.
When we visit /user/1 , it will send a response id: 1 ; if we visit /user/2 , response will be id: 2 .
We also can add multiple dynamic segments in one path:
#[get("/user/<id>/<name>")]
fn index(id : i32, name: String) -> String {
format!("id: {}, name: {}", id, name)
}





