我正在和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
执行借阅req
和req.respond()
"移动" req
因为它接受self
。我不确定我应该在这做什么,有人可以帮我理解吗?
答案 0 :(得分:5)
在移动值之前,您已确保借用已结束。要调整您的代码:
fn handle_request(req: Request) {
{
let headers = req.headers();
// working with headers
}
let res = Response::from_string("hi");
req.respond(res);
}
借用只会持续到函数顶部的块,因此在块结束后,您可以自由移动res
。