I have the following code in a program using duckdb-rs that compiles without error.
/// The context of execution
#[derive(Debug)]
struct Context<'a> {
/// The connection to the database
conn: Option<Connection>,
/// The command line parameters
cli: &'a Cli,
/// Identifier of the root directory
root_id: u64,
/// Appenders to add rows to tables
//# apnd_global_error: Option<Appender<'a>>,
}
/// Prepare the context of execution based on command line parameters
fn get_context(cli: &Cli) -> Result<Context, CfaError> {
let c = &db_open(cli)?;
let conn = c.try_clone()?;
//# let apnd_global_error = c.appender("global_error")?;
let ctx = Context {
conn: Some(conn),
cli,
root_id: 0,
//# apnd_global_error: Some(apnd_global_error),
};
Ok(ctx)
}
/// Open the database and returns a connection handle.
fn db_open(cli: &Cli) -> Result<Connection, CfaError> {
...
}
But as soon I uncomment the //#
lines, to add an Appender
to the context of execution, the compiler raises the error [E0515]
.
error[E0515]: cannot return value referencing temporary value
--> src/lib.rs:504:5
|
480 | let c = &db_open(cli)?;
| ------------- temporary value created here
...
504 | Ok(ctx)
| ^^^^^^^ returns a value referencing data owned by the current function
I understand I can't return a temporary value allocated on the function stack, but I don't understand how ctx
would get that temporary. The error from the compiler says that the value is created and assigned to c
, but I don't understand how ctx
is referencing it. I've tried boxing c
to have it created on the heap instead of stack without success.
Can someone explain me what's happening there and orient me how it can be solved?