I'm playing with Rust and tiny-http. I've created a function in which I'm messing with the headers of request and then sending response:
fn handle_request(req: Request) {
let headers = req.headers();
// working with headers
let res = Response::from_string("hi");
req.respond(res);
}
It fails 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 kinda understand that req.headers()
accepts &self
which performs borrowing req
and req.respond()
"moves" req
since it accepts self
. I'm not sure what I should do here, can someone help me understand that?
You have make sure the borrow ends before you move the value. To adapt your code:
fn handle_request(req: Request) {
{
let headers = req.headers();
// working with headers
}
let res = Response::from_string("hi");
req.respond(res);
}
The borrow will only last for the block at the top of the function, so after the end of the block you're free to move res
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With