I'm writing an application that communicates with a database. I thought the new
method in the Repository
would initialize the struct member conn
to the reference of MysqlConnection::establish(...)
in the below code.
struct Repository<'a> {
conn: &'a MysqlConnection,
}
impl<'a> Repository<'a> {
pub fn new() -> Self {
Self {
conn: &MysqlConnection::establish(...)
}
}
pub fn new_with_connection(conn: &'a MysqlConnection) -> Self {
Self {
conn
}
}
}
fn main() {
// do something...
}
However, I got an error when I try to build the application.
error[E0515]: cannot return value referencing temporary value
--> src/main.rs:7:9
|
7 | / Self {
8 | | conn: &MysqlConnection::establish(...)
| | ------------------------------- temporary value created here
9 | | }
| |_________^ returns a value referencing data owned by the current function
I've learned from the book that a function cannot return a dangling reference, but I can't find the way to avoid it in this case. Can I assign a reference to conn
in the new
method while keeping conn
as a reference type?