rust - 如何在 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
在方法中分配引用吗?new
conn
解决方案
推荐阅读
- julia - 进行有条件的内部函数赋值
- jenkins - 如何在 jenkins windows 命令中获取 BRANCH_NAME
- javascript - JavaScript - 如何从数组数组中删除所有字母
- java - 使用 GSON 转义字符串反斜杠
- python - 是否可以在 CentOS 7 上使用带有网状结构的 RStudio Server 配置 conda python 环境?
- button - Gnuplot 按钮灰显
- android - 由于未启用 multidex 支持,Android 应用程序崩溃?
- f# - 使用反射评估模块的静态构造函数
- sql - 执行 SQL 查询以从数据库中删除未使用的用户
- java - 如何存储具有不同行为的相似对象?