首页 > 解决方案 > 如何在 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

我从书中了解到,函数不能返回悬空引用,但在这种情况下我找不到避免它的方法。我可以在保持引用类型的同时conn在方法中分配引用吗?newconn

标签: rustdangling-pointer

解决方案


推荐阅读