2015-06-24 28 views
3

我在玩Rust和tiny-http。我已经创造了一种我与请求的报头搞乱,然后发送响应函数:因为借用而无法移出`req`

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。我不确定我应该在这里做什么,有人能帮我理解吗?

回答

4

在移动该值之前,您必须确定借款已结束。为适应您的代码:

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

的借将仅持续在函数的顶部块,所以该块结束后,你可以自由地移动res

+0

还有http://doc.rust-lang.org/std/mem/fn.drop.html; ) – ArtemGr

+3

这不会消除借贷,它只会降低价值。 –

+0

@SteveKlabnik文档中的示例如何? '下降(mutable_borrow)'? – ArtemGr

相关问题