Rust 基于petgraph的随机游动

Rust 基于petgraph的随机游动,rust,graph-algorithm,petgraph,Rust,Graph Algorithm,Petgraph,我正在尝试使用petgraph板条箱在有向图上实现随机游动 到目前为止,我已经定义了一个RandomWalk结构,它实现了Walker特性: extern crate petgraph; // 0.4.13 use petgraph::visit::{GraphBase, Walker}; use petgraph::Direction; pub struct RandomWalk<G> where G: GraphBase { next: G::NodeId,

我正在尝试使用
petgraph
板条箱在有向图上实现随机游动

到目前为止,我已经定义了一个
RandomWalk
结构,它实现了
Walker
特性:

extern crate petgraph; // 0.4.13
use petgraph::visit::{GraphBase, Walker};
use petgraph::Direction;

pub struct RandomWalk<G> 
    where G: GraphBase
{
   next: G::NodeId, 
}

impl<G> Walker<G> for RandomWalk<G>
    where G: GraphBase
{
   type Item = G::NodeId; 

   fn walk_next(&mut self, graph: G) -> Option<Self::Item> {
       // Even this deterministic walk does not work:
       graph.neighbors_directed(self.next, Direction::Incoming).next()
   }
}

我真的不明白petgraph API是如何工作的,
GraphBase
不是正确的类型吗?

如果您了解编译器,解决方案是非常清楚的。
Rust不会对类型进行任何假设,除非您指定它,例如,您不能将两个类型
t
添加在一起,除非实现该特性。然后您可以编写
T+T

你的问题很相似

您正在尝试使用未为
G
实现的函数
neights\u directed
(在您的示例中,该函数绑定到
GraphBase
)。相反,您必须指定
G
还必须通过将该特性添加到impl块来实现该特性

impl<G> Walker<G> for RandomWalk<G> where G: GraphBase + IntoNeighborsDirected
impl Walker for RandomWalk,其中G:GraphBase+IntoNeighborsDirected

这将告诉编译器,
G
实现了方法
neights\u directed
,您可以使用它()

,正如错误消息所述,如果您真的想在
G
上泛型,正确的特征称为
intoneightorsdirected
。如果您只是想让某些东西正常工作,那么首先为具体类型(例如,
Graph
)实现此功能可能会更快。请始终尝试为我们提供一个解决方案。我编辑了它,所以你可以看到,我的意思。现在,我可以将代码复制并粘贴到操场(最好为我们提供一个操场;),然后开始解决您的问题。谢谢!我不知道铁锈操场也支持板条箱-这是一个漂亮的功能。
impl<G> Walker<G> for RandomWalk<G> where G: GraphBase + IntoNeighborsDirected