因为它是借来的,所以不能搬出`req`

时间:2015-06-24 21:47:34

标签: rust

我正在和Rust和tiny-http一起玩。我创建了一个函数,我在其中弄乱了请求的标题然后发送响应:

fn handle_request(req: Request) {
    let headers = req.headers();
    // working with headers
    let res = Response::from_string("hi");
    req.respond(res);
}

失败并显示错误:

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

所以我理解req.headers()接受&self执行借阅reqreq.respond()"移动" req因为它接受self。我不确定我应该在这做什么,有人可以帮我理解吗?

1 个答案:

答案 0 :(得分:5)

在移动值之前,您已确保借用已结束。要调整您的代码:

fn handle_request(req: Request) {
    {
        let headers = req.headers();
        // working with headers
    }
    let res = Response::from_string("hi");
    req.respond(res);
}

借用只会持续到函数顶部的块,因此在块结束后,您可以自由移动res