How to return a structure with a temporary value

Conn {
10 | |             connection: &Connection::open(db_name).expect("can't open sqlite db"),
   | |                          -------------------------------------------------------- temporary value created here
11 | |         }
   | |_________^ returns a value referencing data owned by the current function

use rusqlite::Connection;

pub struct Conn<'a> {
    connection: &'a Connection,
}

impl<'a> Conn<'a> {
    pub fn new(db_name: &str) -> Conn {
        Conn {
            connection: &Connection::open(db_name).expect("can't open sqlite db"),
        }
    }

It shouldn't be a reference:

pub struct Conn {
    connection: Connection,
}
1 Like

How to return a structure with a temporary value

"Temporary" means something is about to be destroyed. When is it destroyed? Well, right before new returns. new shouldn't return something that was already destroyed before new returned.

1 Like

can you tell why it doesn’t work with the reference?

Because when you have a reference in a struct, that means your struct doesn't own that value. Something else owns it, and your struct can't outlive the owner.

2 Likes

Can I fix the error in another way? for example lifetime?

Yes, take ownership of the connection:

pub struct Conn {
    connection: Connection,
}

Yes, this method works, but is there another way? or is this the only way?

What are you looking for in another way that this one doesn't give you?

I am studying rust and I am interested to know how rust works.

Well if you want to take ownership, that is the way. If you want it to be a reference, then you can do like below, but then the caller has to create the connection, and the caller owns the connection, and your struct will not be able to outlive the connection that it has a reference to.

pub struct Conn<'a> {
    connection: &'a Connection,
}

impl<'a> Conn<'a> {
    pub fn new(db: &'a Connection) -> Self {
        Conn {
            connection: conn,
        }
    }
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.