相关疑难解决方法(0)

返回迭代器(或任何其他特征)的正确方法是什么?

以下Rust代码编译并运行没有任何问题.

fn main() {
    let text = "abc";
    println!("{}", text.split(' ').take(2).count());
}
Run Code Online (Sandbox Code Playgroud)

在那之后,我尝试了类似的东西....但它没有编译

fn main() {
    let text = "word1 word2 word3";
    println!("{}", to_words(text).take(2).count());
}

fn to_words(text: &str) -> &Iterator<Item = &str> {
    &(text.split(' '))
}
Run Code Online (Sandbox Code Playgroud)

主要问题是我不确定函数to_words()应该具有什么返回类型.编译器说:

error[E0599]: no method named `count` found for type `std::iter::Take<std::iter::Iterator<Item=&str>>` in the current scope
 --> src/main.rs:3:43
  |
3 |     println!("{}", to_words(text).take(2).count());
  |                                           ^^^^^
  |
  = note: the method `count` exists but the following trait bounds were not satisfied:
          `std::iter::Iterator<Item=&str> : std::marker::Sized`
          `std::iter::Take<std::iter::Iterator<Item=&str>> …
Run Code Online (Sandbox Code Playgroud)

rust

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

如何编写一个返回对自身引用的迭代器?

我无法表达Iterator实现的返回值的生命周期.如何在不更改迭代器的返回值的情况下编译此代码?我希望它返回一个引用的向量.

很明显,我没有正确使用生命周期参数,但在尝试了我放弃的各种方法之后,我不知道如何处理它.

use std::iter::Iterator;

struct PermutationIterator<T> {
    vs: Vec<Vec<T>>,
    is: Vec<usize>,
}

impl<T> PermutationIterator<T> {
    fn new() -> PermutationIterator<T> {
        PermutationIterator {
            vs: vec![],
            is: vec![],
        }
    }

    fn add(&mut self, v: Vec<T>) {
        self.vs.push(v);
        self.is.push(0);
    }
}

impl<T> Iterator for PermutationIterator<T> {
    type Item = Vec<&'a T>;
    fn next(&mut self) -> Option<Vec<&T>> {
        'outer: loop {
            for i in 0..self.vs.len() {
                if self.is[i] >= self.vs[i].len() {
                    if i == 0 {
                        return None; // we are done …
Run Code Online (Sandbox Code Playgroud)

iterator lifetime rust

24
推荐指数
3
解决办法
9208
查看次数

标签 统计

rust ×2

iterator ×1

lifetime ×1