rust - Refactoring messes up mutable borrow - why? -
i'm trying understand why following refactoring result in error, though should have same behaviour:
before:
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"); ... after:
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"); this results in error:
src/main.rs:64:20: 64:34 error: cannot borrow `req.extensions` immutable because `*req` borrowed 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; mutable borrow prevents subsequent moves, borrows, or modification of `*req` until 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 } so problem get_pool_connection borrows request , gives connection prevents further req use. why happen? req guaranteed use @ least same lifetime returned pooledconnection. it's not moved either, passed &mut. prevents request being used?
and why error *req borrowed, when both local req , function parameter references?
that's meaning of lifetime annotations. if have function having prototype:
fn get_bar<'a>(&'a foo) -> bar<'a> { ... } it means bar object returned owns lifetime tied 1 of foo object. consequence:
- the
barobjects borrowsfooobject long alive - the
barobject not allowed outlivefooobject.
in case, connection of type pooledconnection<'a, ...>, 'a lifetime defined in &'a mut req, considered mutable borrow of req.
it worked before refactoring, because lifetime of connection linked lifetime of pool, didn't borrow req not hold lifetime parameter.
as refactoring forces connection borrow req, not needed before, maybe not appropriate refactoring.
Comments
Post a Comment