0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Simon Park
  • 694
  • 1
  • 7
  • 18
  • As the book you linked to says: *The solution here is to return the `String` directly*. Thus, store the connection directly: `conn: MysqlConnection`. No references. – Shepmaster Sep 08 '20 at 16:54
  • See also [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/q/32300132/155423) – Shepmaster Sep 08 '20 at 16:55

0 Answers0