如何在Rust中创建一个包含引用字段的新实例?

问题描述

我正在编写一个数据库通信的应用程序。我认为new中的Repository方法会将结构成员conn初始化为以下代码MysqLConnection::establish(...)的引用。

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...
}

但是,尝试构建应用程序时出现错误

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

我从the book中学到了一个函数不能返回悬挂的引用,但是在这种情况下我找不到避免它的方法。我可以在将conn保留为引用类型的同时,在new方法中为conn分配引用吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)