我的项目是这样设置的:
src/lib/rustic_io.rs
src/lib/server.rs
src/main.rs
main.rs
#[path="lib/rustic_io.rs"]
mod rustic_io;
fn main() {
// Setup information (Server is not started yet)
let mut server = rustic_io::listen("127.0.0.1", 1338);
// Event with data to listen for
server.on("connection", |data: &str| {
// Do stuff in here with data
});
// Start server
server.start();
}
rustic_io.rs
mod server;
/*
* Returns a new Server to start WebSocket Protocol
*/
pub fn listen(ip_addr: &str, port_num: u16) -> server::Server {
server::Server::new(String::from_str(ip_addr), port_num)
}
server.rs
pub struct Server<'srv> {
ip: String,
port: u16,
events: Vec<Event<'srv>>
}
impl &'a Server {
// Constructs a Server object
pub fn new<'a>(ip_addr: String, port_num: u16) -> Server<'a> {
Server {
ip: ip_addr,
port: port_num,
events: Vec::new()
}
}
pub fn on(&self, event: &str, execute: |data: &str|) {
// Do some stuff
}
pub fn start(&self) {
// Start up all the things
}
}
mod event {
pub struct Event<'a> {
name: String,
execute: |data: &str|:'a
}
}
一切正常,直到我想开始添加 Event
的矢量输入 Server
结构。为了将闭包添加为属性,它需要一个生命周期。在 SO 的帮助下得到了它。然后,为了有一个Vec<Event>
在Server
struct,它也需要一个生命周期。一旦服务器结构全部生命周期结束,impl
现在需要生命。在实现部分获得生命周期后,当我尝试编译时,我现在得到 p>
error: failed to resolve. Not a module `Server`
指向这个语句:server::Server::new(String::from_str(ip_addr), port_num)
当涉及到在函数内的各种变量上使用生命周期时,我觉得我对生命周期有很好的了解,但是在设计自己的结构和实现时对于生命周期是什么却一无所知。当实现使用生命周期时,为什么服务器模块停止变得可解析?我觉得我正在以完全相反的方式来解决这个问题,并且让生命周期说明符失控......
最佳答案
这不是一生的问题。我能够让您的代码通过以下方式进行编译:
impl &'a Server { ... }
不是有效的语法。将其更改为impl<'a> Server<'a> { ... }
更改
Vec<Event<'srv>>
至Vec<event::Event<'srv>>
.
您还可以更改 fn new<'a>
至 fn new
在 impl block 中。
关于struct - 添加到 struct/impl 的生命周期使模块无法解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25189453/