问题描述
我正在编写一个与数据库通信的应用程序。我认为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 (将#修改为@)