【发布时间】:2015-05-15 05:24:09
【问题描述】:
我试图理解为什么以下重构会导致错误,即使它实际上应该具有相同的行为:
之前:
fn req_handler(req: &mut Request) -> IronResult<Response> {
let pool = req.get::<Read<Database>>().ok().expect("database component not initialised");
let connection = pool.get().unwrap();
let maybe_id = req.extensions.get::<Router>().unwrap().find("id");
...
之后:
pub fn get_pool_connection<'a, 'b, 'c>(req: &'a mut Request<'b, 'c>) -> PooledConnection<'a, PostgresConnectionManager> {
let pool = req.get_ref::<Read<Database>>().ok().expect("database component not initialised");
pool.get().unwrap()
}
fn req_handler(req: &mut Request) -> IronResult<Response> {
let connection = get_pool_connection(req);
let maybe_id = req.extensions.get::<Router>().unwrap().find("id");
这会导致错误:
src/main.rs:64:20: 64:34 error: cannot borrow `req.extensions` as immutable because `*req` is also borrowed as mutable
src/main.rs:64 let maybe_id = req.extensions.get::<Router>().unwrap().find("id");
^~~~~~~~~~~~~~
src/main.rs:62:42: 62:45 note: previous borrow of `*req` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `*req` until the borrow ends
src/main.rs:62 let connection = get_pool_connection(req);
^~~
src/main.rs:76:2: 76:2 note: previous borrow ends here
src/main.rs:61 fn req_handler(req: &mut Request) -> IronResult<Response> {
...
src/main.rs:76 }
所以问题是get_pool_connection 借用请求并返回connection,这阻止了req 的进一步使用。但是为什么会这样呢? req 保证使用至少与返回的 PooledConnection 相同的生命周期。它也没有被移动,它只是作为&mut 传递的。那么是什么阻止了请求被使用呢?
当本地req和函数参数都是引用时,为什么错误说*req被借用了?
【问题讨论】:
-
错误说
*req是借用的,因为req是一个引用。毕竟,您通常借用一些拥有的数据作为参考点,而不是参考本身。