Skip to content
This repository has been archived by the owner on Oct 29, 2021. It is now read-only.

Can't use the header value from context in Response due to owndership #65

Open
jk-gan opened this issue May 26, 2020 · 1 comment
Open
Labels
bug Something isn't working
Projects
Milestone

Comments

@jk-gan
Copy link
Member

jk-gan commented May 26, 2020

I want to use the header value from request and return in Response:

#[derive(Serialize)]
struct IndexResponse {
  message: String,
}

async fn index(ctx: Context) -> ContextResult {
  let hello = ctx.headers()
                .get("hello")
                .and_then(|v| v.to_str().ok())
                .unwrap_or_else(|| "world");

  ctx.build_json(IndexResponse { message: hello.to_owned() }).ok()
}

and I get the error:

❯ cargo run
   Compiling messages-obsidian v0.1.0 (/Users/jkgan/Developer/Rust/messages-obsidian)
error[E0505]: cannot move out of `ctx` because it is borrowed
  --> src/lib.rs:30:3
   |
25 |   let hello = ctx.headers()
   |               --- borrow of `ctx` occurs here
...
30 |   ctx.build_json(IndexResponse { message: hello.to_owned() }).ok()
   |   ^^^ move out of `ctx` occurs here       ----- borrow later used here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0505`.
error: could not compile `messages-obsidian`.

To learn more, run the command again with --verbose.
@jk-gan jk-gan added the bug Something isn't working label May 26, 2020
@jk-gan jk-gan added this to To do in Obsidian via automation May 26, 2020
@jk-gan jk-gan added this to the v0.3 milestone May 26, 2020
@jk-gan jk-gan changed the title Can't use the header value from context in Response Can't use the header value from context in Response due to owndership May 26, 2020
@jk-gan
Copy link
Member Author

jk-gan commented May 31, 2020

I fixed it by making the method doesn't own the ctx:

pub fn build(&self, res: impl Responder) -> ResponseBuilder {
    ResponseBuilder::new(res.respond_to())
}

and now I'm getting this error for closure:

error[E0515]: cannot return value referencing function parameter `ctx`
 --> examples/hello.rs:7:33
  |
7 |     app.get("/", |ctx: Context| async { ctx.build("Hello World").ok() });
  |                                 ^^^^^^^^---^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |                                 |       |
  |                                 |       `ctx` is borrowed here
  |                                 returns a value referencing data owned by the current function

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working
Projects
Obsidian
  
To do
Development

No branches or pull requests

1 participant