Can't get out of `req` because it's borrowed
I am playing with Rust and tiny-http . I created a function where I fiddled with the request headers and then sent the response:
fn handle_request(req: Request) {
let headers = req.headers();
// working with headers
let res = Response::from_string("hi");
req.respond(res);
}
Error with error:
main.rs:41:5: 41:8 error: cannot move out of `req` because it is borrowed
main.rs:41 req.respond(res);
^~~
main.rs:27:19: 27:22 note: borrow of `req` occurs here
main.rs:27 let headers = req.headers();
^~~
error: aborting due to previous error
So, I understand what is req.headers()
taking &self
, which is borrowing req
and req.respond()
"move" req
as it is taking self
. I'm not sure what I should be doing here, can someone help me figure this out?
source to share
You must make sure the loan ends before you move the value. To set up the code:
fn handle_request(req: Request) {
{
let headers = req.headers();
// working with headers
}
let res = Response::from_string("hi");
req.respond(res);
}
The loan will only last for the block at the top of the function, so after the block ends, you can move res
.
source to share