Rust 结构中的引用

Rust 结构中的引用,rust,Rust,我试图将有关inotify事件和hashmap的信息放入一个结构中,其中inotify watchid作为键,文件名作为值 extern crate inotify; use inotify::INotify; use std::sync::{Arc, Mutex}; use std::collections::HashMap; struct Notificator { inotify: INotify, watch_service: Arc<Mutex<HashM

我试图将有关inotify事件和hashmap的信息放入一个结构中,其中inotify watchid作为键,文件名作为值

extern crate inotify;
use inotify::INotify;
use std::sync::{Arc, Mutex};
use std::collections::HashMap;

struct Notificator {
    inotify: INotify,
    watch_service: Arc<Mutex<HashMap<inotify::wrapper::Watch, Arc<String>>>>,
}

impl Notificator {
    pub fn new() -> Notificator {
        Notificator {
            inotify: INotify::init().unwrap(),
            watch_service: Arc::new(Mutex::new(HashMap::new())),
        }
    }

    pub fn resolving_events(&mut self) {
        {
            let mut events = self.check_for_events();
            self.events_execution(events);
        }

    }

    fn check_for_events(&mut self) -> &[inotify::wrapper::Event] {
        self.inotify.available_events().unwrap()
    }

    fn events_execution(&self, events: &[inotify::wrapper::Event]) {
        for event in events.iter() {

        }
    }
}
我认为最好的解决方案是在Notificator结构中用watch_服务以某种方式分离inotify变量,但我不能取消对
self.check_的引用以查找事件()因为我收到

src/main.rs:203:17: 203:27 error: the trait bound `[inotify::wrapper::Event]: std::marker::Sized` is not satisfied [E0277]
src/main.rs:203             let mut events = *self.check_for_events();
我理解问题的核心:我试图通过
检查\u事件
借用引用,然后在
事件执行中使用它作为参数,这也需要
self
作为参数,但我不知道如何解决它。

这是借用检查器()中的一个参数。在
&T
超出范围之前,您不能让函数将
&T
带到对象并返回
&T
而不失去再次访问该对象的能力。由于
inotify
的实现方式,您无法解决此问题

但是您需要创建一个不获取新数据的
get\u available\u notifications
方法。这样,您可以调用一次
可用的\u通知
,并删除返回的值。然后调用
get\u available\u notifications
(它不需要
&mut INotify
,只需要
&INotify
)并从那里开始工作。

您可以做的一件事,尽管它不是很优雅,就是让您的可变方法使用它的可变借用并返回一个您可以使用的可变借用:

pub fn resolving_events(&mut self) {
    let (slf, events) = self.check_for_events();
    slf.events_execution(events);

}

fn check_for_events(&mut self) -> (&Self, &[inotify::wrapper::Event]) {
    let events = self.inotify.available_events().unwrap();
    (&self, events)
}

我在上做了一个小的概念证明(使用
u64
的向量作为可变状态,但原理类似)。重构您的代码可能会更干净,这样一些外部客户端可以(可变地)借用
通知程序,生成事件,释放借用,然后(不可变地)借用它来处理它们…

在事件执行中是否使用
self
?如果不是,不将其作为参数可能会解决您的问题。@Noctua,我忘了在post中编写它,但是的,我在事件执行中使用self。好的,我试图重写代码,现在我有了
“self”在
check_for_events
函数的第二行中活得不够长
。我想我的代码在返回
和self时可能不正确:返回
self
(声明为
和self
)似乎工作得很好:
fn check_for_events(&mut self)>(&self,&[inotify::wrapper::Event])){let events=self.inotify.available_events().unwrap();(self,events)}
在第二行
中不能将“*self”作为不可变借用,因为“self.inotify”也作为可变借用
在第一行
中,前面借用了“self.inotify”
pub fn resolving_events(&mut self) {
    let (slf, events) = self.check_for_events();
    slf.events_execution(events);

}

fn check_for_events(&mut self) -> (&Self, &[inotify::wrapper::Event]) {
    let events = self.inotify.available_events().unwrap();
    (&self, events)
}