使用petgraph随机漫步

时间:2018-10-18 11:53:33

标签: rust graph-algorithm

我正在尝试使用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()
   }
}

但是,我得到了错误:

error[E0599]: no method named `neighbors_directed` found for type `G` in the current scope
  --> src/lib.rs:50:11
   |
50 |     graph.neighbors_directed(self.next, Direction::Incoming).next()
   |           ^^^^^^^^^^^^^^^^^^
   |
   = note: the method `neighbors_directed` exists but the following trait bounds were not satisfied:
           `&G : petgraph::visit::IntoNeighborsDirected`
   = help: items from traits can only be used if the trait is implemented and in scope
   = note: the following trait defines an item `neighbors_directed`, perhaps you need to implement it:
           candidate #1: `petgraph::visit::IntoNeighborsDirected`

我不太了解petgraph API的工作方式,GraphBase是不正确的类型吗?

1 个答案:

答案 0 :(得分:1)

如果您了解编译器,则解决方案非常安静。
Rust不会假设有关该类型的任何信息,除非您进行指定,例如除非实现Add特性,否则您不能将两种类型的T一起添加。然后,您可以编写T + T
您的问题非常相似。

您正在尝试使用neighbors_directed尚未实现的功能G(在示例中已绑定到GraphBase)。相反,您必须指定G还必须通过将特征IntoNeighborsDirected添加到您的impl块中来实现。

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

这将告诉编译器G已实现方法neighbors_directed,您可以使用它(playground