3

pretty new to rust and trying to write a simple web server using Axum. I encountered the following error during compilation:

    error: higher-ranked lifetime error
   |
16 |         .route("/login", post(login));
   |                          ^^^^^^^^^^^
   |
   = note: could not prove `for<'a> fn(Json<Credentials<'a>>) -> impl Future<Output = Json<Value>> {login}: Handler<(axum_core::extract::private::ViaRequest, Json<Credentials<'a>>), ()>`

I'm not sure what does it mean? Would anyone be able to help on this?

This can be resolved if the struct does not use references. But am trying to not copy the values

Below is the snippet of the code.

use axum::{
    routing::post,
    Json, Router,
};
use serde::{Deserialize};
use serde_json::{json, Value};

pub async fn get_routers() -> Router {
    // Build our application by creating our router.
    let routers = Router::new()
        .route("/login", post(login));

    routers
}

async fn login(Json(credentials): Json<Credentials<'_>>) -> Json<Value> {
    let username = credentials.username;
    let password = credentials.password;
    // some other codes here
    Json(json!({ "test": "test", "test1": "test1" }))
}

#[derive(Deserialize, Debug, Clone)]
struct Credentials<'r> {
    username: &'r str,
    password: &'r str,
}
Ruster
  • 37
  • 4
  • Why do you use `&str`? You should be using `String`. – Chayim Friedman Apr 30 '23 at 09:57
  • I just want to use it as reference instead of copying the value? Is this not allowed, hence causing the error? – Ruster Apr 30 '23 at 15:12
  • 1
    Saying "not allowed" is too strong because there is a use-case to using `&str`, but you should use `String`. And yes, this is the cause of the error. – Chayim Friedman Apr 30 '23 at 15:29
  • Deserializing JSON into a `&str` is almost never what you want to do, try `let a: &str = serde_json::from_str(r#""\n""#).unwrap();` – cafce25 Apr 30 '23 at 15:47
  • Thanks! Do you mind explain why deserialising into &str is not desirable and what would be the use case for it? My return value is not a reference to these, so I don't see a lifetime issue here. I just want to use the references of these values to perform some validation, so I don't want to allocate new memory for them since I'm also not modifying it. Hence, would like to understand a bit more on the error – Ruster May 01 '23 at 01:40
  • 1
    Using `&str` has place in the so-called "zero-copy deserialization", but it is almost never what you want: it is more complicated, serde has minimum support for it, and it is not fully supported in JSON because escape sequences in the string may force the deserializer to allocate. – Chayim Friedman May 03 '23 at 13:28
  • Yeah I know on the escape sequences but I did some manipulation to avoid that, so not an issue for me. I guess I will use String for this. Thanks for all the help! – Ruster May 05 '23 at 02:36

0 Answers0