相关疑难解决方法(0)

如何为一个简单的结构实现Iterator和IntoIterator?

有人会如何实现以下结构的特征IteratorIntoIterator特征?

struct Pixel {
    r: i8,
    g: i8,
    b: i8,
}
Run Code Online (Sandbox Code Playgroud)

我尝试了以下各种形式但没有成功.

impl IntoIterator for Pixel {
    type Item = i8;
    type IntoIter = Iterator<Item=Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        [&self.r, &self.b, &self.g].into_iter()
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码给了我一个编译错误

error[E0277]: the trait bound `std::iter::Iterator<Item=i8> + 'static: std::marker::Sized` is not satisfied
 --> src/main.rs:7:6
  |
7 | impl IntoIterator for Pixel {
  |      ^^^^^^^^^^^^ the trait `std::marker::Sized` is not implemented for `std::iter::Iterator<Item=i8> + 'static`
  |
  = note: `std::iter::Iterator<Item=i8> + 'static` does …
Run Code Online (Sandbox Code Playgroud)

iterator rust

43
推荐指数
2
解决办法
2万
查看次数

在迭代递归结构时无法获得可变引用:不能一次多次借用可变引用

我试图迭代地导航递归数据结构,以便在某个位置插入元素.根据我的有限理解,这意味着对结构的根进行可变引用,并通过对其跟随者的引用连续替换它:

type Link = Option<Box<Node>>;

struct Node {
    next: Link
}

struct Recursive {
    root: Link
}

impl Recursive {
    fn back(&mut self) -> &mut Link {
        let mut anchor = &mut self.root;
        while let Some(ref mut node) = *anchor {
            anchor = &mut node.next;
        }
        anchor
    }
}
Run Code Online (Sandbox Code Playgroud)

(Rust操场链接)

但是,这失败了:

error[E0499]: cannot borrow `anchor.0` as mutable more than once at a time
  --> src/main.rs:14:24
   |
14 |         while let Some(ref mut node) = *anchor {
   |                        ^^^^^^^^^^^^
   |                        | …
Run Code Online (Sandbox Code Playgroud)

mutable rust borrowing

16
推荐指数
3
解决办法
2405
查看次数

如何构建一个迭代器来递归地遍历文件树?

我想在对每个级别上的兄弟节点进行排序时,一个接一个地懒惰地消耗文件树的节点。

在 Python 中,我会使用同步生成器:

def traverse_dst(src_dir, dst_root, dst_step):
    """
    Recursively traverses the source directory and yields a sequence of (src, dst) pairs;

    """
    dirs, files = list_dir_groom(src_dir) # Getting immediate offspring.

    for d in dirs:
        step = list(dst_step)
        step.append(d.name)
        yield from traverse_dst(d, dst_root, step)

    for f in files:
        dst_path = dst_root.joinpath(step)
        yield f, dst_path
Run Code Online (Sandbox Code Playgroud)

在 Elixir 中,一个(惰性)流:

def traverse_flat_dst(src_dir, dst_root, dst_step \\ []) do
  {dirs, files} = list_dir_groom(src_dir) # Getting immediate offspring.

  traverse = fn d ->
    step = dst_step …
Run Code Online (Sandbox Code Playgroud)

tree recursion iterator rust

0
推荐指数
1
解决办法
2156
查看次数

标签 统计

rust ×3

iterator ×2

borrowing ×1

mutable ×1

recursion ×1

tree ×1