我是一个有用的助手,可以为您翻译文本。
这会导致错误:
所以问题在于
为什么错误提示说
(相关文档:Request,Pool)
我试图理解为什么以下重构会导致错误,即使它应该有效地具有相同的行为:
之前:
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
和函数参数都是引用时?(相关文档:Request,Pool)
*req
被借用了,这是因为req
是一个引用。毕竟,通常您会借用被引用指向的某些拥有数据,而不是引用本身。 - Vladimir Matveev