我在正确理解 Rust 中的生命周期概念时遇到了一些麻烦。特别是在涉及结构的对象本身和结构的成员时。
以下最小示例显示了我遇到的一个问题:
use redis::{Connection, PubSub};
pub struct Db<'a> {
conn: Connection,
pubsub: Option<PubSub<'a>>
}
impl<'a> Db<'a> {
fn open(address: &str) -> Self {
let client = redis::Client::open(address).unwrap();
let conn = client.get_connection().unwrap();
Self {conn, pubsub: None}
}
fn subscribe(&'a mut self) {
let pubsub = self.conn.as_pubsub();
self.pubsub = Some(pubsub)
}
}
fn main() {
let mut db = Db::open("localhost");
db.subscribe();
}
Run Code Online (Sandbox Code Playgroud)
编译结束并出现以下错误:
error[E0597]: `db` does not live long enough
--> src/main.rs:22:5
|
22 | db.subscribe();
| ^^^^^^^^^^^^^^ borrowed value …Run Code Online (Sandbox Code Playgroud) rust ×1