I'm getting the classic error[E0515]: cannot return value referencing function parameter whatever
, and while I very much understand what's wrong with the trivial example given by the compiler:
fn get_dangling_reference() -> &'static i32 {
let x = 0;
&x
}
I do not understand why my code yields this error when using a closure with map
, but NOT when using the same value (conn
, in the below example) without a closure. Of note, I am using the Rocket framework, and the Outcome<S,E,F>
type is described here: rocket::outcome - Rust and defined here: Outcome in rocket::outcome - Rust . The problem occurs when using Outcome::map
which takes a closure having one parameter of type S
. It does NOT occur when I unwrap
and use S
directly:
/// validate permissions of OnBehalfOf
/// by checking against database agents/principals
async fn validate_obo_permissions<'r>(
_req: &'r Request<'_>,
obo: &OnBehalfOf,
) -> Result<bool, AuthorizationError> {
// Request guard yields Outcome<AppdataDb, _, _>
let maybe_conn = AppdataDb::from_request(_req).await;
// async closures are unstable hence we await later
/*
maybe_conn.map(|conn| {
conn.run(move |c| { // `conn is borrowed here`
AgentPrincipal::validate_pair(agent_id, principal_id, c)
.map_err(|_| AuthorizationError)
}) // -> Future<Result<bool, some_Error>, _>
}) // `returns a value referencing data owned by the current function`
.success_or(AuthorizationError)
.map_err(|_| AuthorizationError)?.await
*/
// `error[E0515]: cannot return value referencing function parameter `conn``
// The below strategy of unwrapping `maybe_conn` works fine, even when I "return"
// a value from the function referencing `conn`
match maybe_conn {
Outcome::Success(_) => {},
Outcome::Failure(_) => { return Err(AuthorizationError); },
Outcome::Forward(_) => { return Err(AuthorizationError); },
};
let conn = maybe_conn.unwrap();
let principal_id = obo.id;
let agent_id = obo.agent_id;
conn.run(move |c| {
AgentPrincipal::validate_pair(agent_id, principal_id, c)
}).await
.map_err(|_| AuthorizationError)
}
As noted in the code, the first, commented-out strategy (functional approach) yields E0515, complaining that conn is borrowed at the indication location (I get this) and "returns a value referencing data owned by the current function". I THINK I get this, and importantly here the "return" is the closure, correct?
In any case, the lower code block (procedural strategy), which unwraps maybe_conn
works fine, even though I am ALSO returning from this function a value referencing conn
.
Is there a way I am missing to make the first strategy work -- alternatively, what am I missing?
Thanks so much in advance