如何使OwningRef与迭代器一起使用?

问题描述

我有一个RwLock保护的全局WORLD,并且我想编写一个函数,该函数读取该锁并返回一个迭代器(类型为Neighbors),该迭代器在{ {1}}存储在全局内部。我正在使用petgraph::stable_graph::StableGraph来处理函数退出后保持读锁保护保持活动的状态,这在过去仅直接返回OwningRef字段时对我有用。我已经提供了一个可编译的示例,并且出现了下面的错误-似乎存在某种类型问题,但我无法弄清楚。我认为这可能与World想要处理一个引用而不是一个包含引用(OwningRef的对象)有关,但是我不确定如何解决

Cargo.toml:

Neighbors

main.rs:

[package]
name = "problem_demo"
version = "0.1.0"
authors = ["Joseph Garvin <joseph.h.garvin@gmail.com>"]
edition = "2018"

[dependencies]
owning_ref="0.4.1"
once_cell="1.4.0"
petgraph={version="0.5.1",features=["serde-1"]}

错误

use std::{sync::RwLock};
use once_cell::sync::OnceCell;
use owning_ref::RwLockReadGuardRef;
use petgraph::stable_graph::{StableGraph,Neighbors};

struct Bar {
    data: i32
}

struct World {
    graph: StableGraph<(),Bar,petgraph::Directed,u32>
}

pub static WORLD: OnceCell<RwLock<World>> = OnceCell::new();

fn neighbors(id: u32) -> Result<RwLockReadGuardRef<'static,World,Neighbors<'static,u32>>,Box<dyn std::error::Error>> {
    RwLockReadGuardRef::new(WORLD.get().unwrap().read().unwrap())
        .try_map(
            |world: &World| -> std::result::Result<Neighbors<'static,u32>,Box<dyn std::error::Error>>
            {
                let neighbors = world.graph.neighbors_directed(
                    petgraph::graph::NodeIndex::new(id as usize),petgraph::Direction::Outgoing
                );

                Ok(neighbors)
            }
        )
}

解决方法

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

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

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