1

我有一个RwLock受保护的 global WORLD,我想编写一个函数来读取它并返回一个迭代器(类型为),该迭代器在存储在全局内部的Neighborsa 中的边上进行迭代。petgraph::stable_graph::StableGraphOwningRef用来处理函数退出后保持读锁守卫活动的问题,这在过去直接返回字段时对我有用World。我已经包含了一个可编译的示例和我在下面遇到的错误 - 似乎存在某种类型问题,但我无法弄清楚。我认为这可能与OwningRef想要处理引用而不是包含引用 ( Neighbors) 的对象有关,但我不确定如何解决这个问题。

货物.toml:

[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"]}

main.rs:

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

                Ok(neighbors)
            }
        )
}

错误:

error[E0271]: type mismatch resolving `for<'r> <[closure@src/main.rs:21:13: 29:14 id:_] as std::ops::FnOnce<(&'r World,)>>::Output == std::result::Result<&'r _, _>`
  --> src/main.rs:20:10
   |
20 |         .try_map(
   |          ^^^^^^^ expected struct `petgraph::stable_graph::Neighbors`, found reference
   |
   = note: expected enum `std::result::Result<petgraph::stable_graph::Neighbors<'static, Bar>, std::boxed::Box<dyn std::error::Error>>`
              found enum `std::result::Result<&_, _>`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0271`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.
4

0 回答 0