我有一个服务器应用程序,我想将套接字和其他信息保存在一个向量中。现在,为了方便起见,我想使用可通过互斥锁访问的全局静态向量 game_sessions
.
我知道保留全局对象在 Rust 中并不是最好的主意,但由于这主要是原型(prototype)工作,所以会大大简化这部分。
错误可以在下面找到,但它要求 Option<&TcpStream>
的生命周期说明符PlayerSession 的属性。
我假设它要求一个`static 生命周期说明符。现在,我明白 Mutex 和 Vec 的生命周期是静态的,但我不明白为什么向量中的元素必须是静态的。
有什么办法可以让它工作吗?我知道还有其他方法可以做到这一点,但我想知道为什么这种特定方法不起作用。
use std::net::{TcpStream};
use std::sync::*;
#[derive(PartialEq)]
pub enum SessionState {
Closed,
Active
}
pub struct PlayerSession {
pub state: SessionState,
pub player_socket: Option<&TcpStream>
}
lazy_static! {
static ref game_sessions: Mutex<Vec<PlayerSession>> = Mutex::new(vec![]);
}
pub fn create_player_session(client_socket: &TcpStream) {
let mut x = game_sessions.lock().unwrap();
x.push(PlayerSession {
state: SessionState::Closed,
player_socket: Some(client_socket)
});
}
构建时,错误是:
error[E0106]: missing lifetime specifier
--> src\sessions.rs:12:31
|
12 | pub player_socket: Option<&TcpStream>
| ^ expected lifetime parameter
仍在学习这门语言,请原谅代码质量不佳,继续努力。
最佳答案
有了这个:
pub struct PlayerSession {
pub state: SessionState,
pub player_socket: Option<&TcpStream>
}
你告诉 rust PlayerSession
可能包含对 TcpStream
的引用。
如果您想在此数据结构中安全地存储对套接字的引用,则需要指定套接字所有者(未在您的代码示例中显示)和 PlayerSession
结构之间的生命周期关系。否则,编译器无法验证套接字是否可能被删除并留下悬空引用。
PlayerSession
结构碰巧存储在静态 Vec
中这一事实并没有改变这一点。
如果您实际上不需要共享套接字,最简单的解决方案可能是让 PlayerSession
拥有套接字,而不是仅仅引用它。
关于rust - 我可以在静态向量中包含非静态结构吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57137790/