如何从特征实现中返回HashMap的键上的迭代器?

问题描述 投票:0回答:1

我正在尝试在Rust中构建一个简单的图形库。任何图都必须实现一个特征Graph。此特征目前仅具有一个功能nodes,它允许使用for-in循环来迭代图的节点。

Graph的实现,MapGraph是围绕HashMap的轻量级包装。 MapGraph必须实现Graph特征方法nodes。我在使它正常工作时遇到问题。

这里是Graph的代码:

pub trait Graph<N> {
    fn nodes(&self) -> Box<dyn Iterator<Item = &N>>;
}

这是MapGraph的代码:

use std::collections::HashMap;

use crate::rep::Graph;

pub struct MapGraph<N> {
    map: HashMap<N, HashMap<N, ()>>
}

impl<N> MapGraph<N> {
    pub fn new(map: HashMap<N, HashMap<N, ()>>) -> Self {
        MapGraph { map }
    }
}

impl<N> Graph<N> for MapGraph<N> {
    fn nodes(&self) -> Box<dyn Iterator<Item=&N>> {
        let keys = self.map.keys();

        Box::new(keys)
    }
}

编译器给出此错误:

error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
  --> src/lib.rs:19:29
   |
19 |         let keys = self.map.keys();
   |                             ^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 18:5...
  --> src/lib.rs:18:5
   |
18 | /     fn nodes(&self) -> Box<dyn Iterator<Item = &N>> {
19 | |         let keys = self.map.keys();
20 | |
21 | |         Box::new(keys)
22 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/lib.rs:19:20
   |
19 |         let keys = self.map.keys();
   |                    ^^^^^^^^
   = note: but, the lifetime must be valid for the static lifetime...
   = note: ...so that the expression is assignable:
           expected std::boxed::Box<(dyn std::iter::Iterator<Item = &N> + 'static)>
              found std::boxed::Box<dyn std::iter::Iterator<Item = &N>>

我发现了与此错误有关的其他参考,但这些情况似乎与我在这里看到的情况不一样。

我正在使用Box,因为Graph特征具有本身返回特征的函数。 What is the correct way to return an Iterator (or any other trait)?将此方法作为一种选择,而我无法实现其他任何一种。如果还有另一种方法可以,那就很好。

我有什么解决此特定问题的选项?

rust graph-theory
1个回答
2
投票

如果您明确指定要返回的特征对象(dyn Iterator)不包含任何超出self的引用,则可以使用。

© www.soinside.com 2019 - 2024. All rights reserved.