0

我正在尝试使用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`

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

4

1 回答 1

1

如果您了解编译器,则解决方案很清楚。
Rust 不对类型做任何假设,除非你指定它,例如你不能将两种类型加T在一起,除非实现Addtrait。然后就可以写了T + T
你的问题非常相似。

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

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

这将告诉编译器,G该方法已neighbors_directed实现并且您可以使用它(操场

于 2018-10-18T12:54:55.760 回答