What Rust feature is this?

Hi all,

I'm looking into the axum crate and the README example shows something I haven't seen before while using Rust - the parameter name is wrapped in a tuple struct. What does this mean and what feature of Rust allows this and also why do something like this?

async fn create_user(
    // this argument tells axum to parse the request body
    // as JSON into a `CreateUser` type
    Json(payload): Json<CreateUser>,    // <<<--- this part here
) -> impl IntoResponse {
...

Thanks for the help!

3 Likes

Function arguments are patterns, so that binds the single T field of struct Json<T>(T) to payload.

As for why, apparently that function doesn't need any Json methods and they didn't want to write json.0 a lot or such.

12 Likes

Interesting! So you can destructure it in the argument itself!

Alright I get it. Thank you @quinedot for that link - it helped a lot. The description in there that helped me the most with this is:

The point is: when you are using pattern matching:

  • you describe the overall shape of the value using a pattern on the left-hand-side of the equality or in the "case arms" of a match expression;
  • while the right-hand-side of the equality, or the so-called discriminator expression of the match will be the value or expression that you are matching against (or, as it's sometimes called, destructuring).
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.