在Rust中,我有很多要管理的接收器对象,但是使用Select遇到生命周期问题

问题描述

由于存在大量对象的可能性,我希望有一种方法可以将它们添加到选择列表中,将其删除以进行处理,然后再添加回去。全部,而不必每次重新添加对象以等待时都重新构建选择列表。看起来像这样:

dragStart()

随着时间的推移,选择列表将包含更多无效条目,然后生效,我将在那时重建它。但是,我不想每次都重建它。这是详细的错误消息:

use std::collections::HashMap;
use crossbeam::{Select,Sender,Receiver};

struct WaitList <'a> {
    sel: Select<'a>,objects: HashMap<u128,Object>,sel_index: HashMap<usize,u128>,}
impl<'a> WaitList<'a> {
    fn new () -> Self { Self { sel: Select::new(),objects: HashMap::new(),sel_index: HashMap::new() } }
    fn select(&self) -> &Object {
        let oper = self.sel.select();
        let index = oper.index();
        let id = self.sel_index.get(&index).unwrap();
        let obj = self.objects.get(&id).unwrap();
        obj.cmd = oper.recv(&obj.receiver).unwrap();
        self.sel.remove(index);
        obj
    }

    fn add_object(&self,object: Object) {
        let id = object.id;
        self.objects.insert(id,object);
        self.add_select(id);
    }

    fn add_select(&self,id: u128) {
        let idx = self.sel.recv(&self.objects.get(&id).unwrap().receiver);
        self.sel_index.insert(idx,id);
    }
}

虽然我相信我理解问题,但哈希表中的接收者借用期限不够长,但我很难找到一个替代方案-而且我没有看到一种干净的借阅信息的方法。我考虑过创建一个包含借用的结构,并在等待sel_index中使用它来代替普通ID,但这会遇到相同的生命周期问题。

    Checking test-select v0.1.0 (/Users/bruce/Projects/rust/examples/test-select)
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> src/main.rs:28:47
   |
28 |         let idx = self.sel.recv(&self.objects.get(&id).unwrap().receiver);
   |                                               ^^^
   |
note: first,the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 27:5...
  --> src/main.rs:27:5
   |
27 | /     fn add_select(&self,id: u128) {
28 | |         let idx = self.sel.recv(&self.objects.get(&id).unwrap().receiver);
29 | |         self.sel_index.insert(idx,id);
30 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:28:34
   |
28 |         let idx = self.sel.recv(&self.objects.get(&id).unwrap().receiver);
   |                                  ^^^^^^^^^^^^
note: but,the lifetime must be valid for the lifetime `'a` as defined on the impl at 9:6...
  --> src/main.rs:9:6
   |
9  | impl<'a> WaitList<'a> {
   |      ^^
note: ...so that the types are compatible
  --> src/main.rs:28:28
   |
28 |         let idx = self.sel.recv(&self.objects.get(&id).unwrap().receiver);
   |                            ^^^^
   = note: expected `&mut crossbeam::Select<'_>`
              found `&mut crossbeam::Select<'a>`

我觉得我缺少某些东西或不了解某些东西,因为似乎要做我想做的事情并不那么困难。我可以想象,选择HashMap来保存对象可能是个问题,在我添加和插入时,Vec感到不对。顺便说一句,HashMap通常不是等待列表的一部分。它是其他事情的一部分,但是无论HashMap居住在哪里,问题仍然存在。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)