Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot move out of `req` because it is borrowed

Tags:

rust

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?

like image 221
franza Avatar asked Jun 24 '15 21:06

franza


1 Answers

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.

like image 193
fjh Avatar answered Nov 15 '22 18:11

fjh