是否有 String::chars 的自有版本? [英] Is there an owned version of String::chars?

查看:26
本文介绍了是否有 String::chars 的自有版本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码无法编译:

use std::str::Chars;

struct Chunks {
    remaining: Chars,
}

impl Chunks {
    fn new(s: String) -> Self {
        Chunks {
            remaining: s.chars(),
        }
    }
}

错误是:

error[E0106]: missing lifetime specifier
 --> src/main.rs:4:16
  |
4 |     remaining: Chars,
  |                ^^^^^ expected lifetime parameter

Chars 不拥有它迭代的字符,并且它的生命周期不能超过它创建的 &strString.

Chars doesn't own the characters it iterates over and it can't outlive the &str or String it was created from.

是否有不需要生命周期参数的 Chars 自有版本,或者我必须自己保留 Vec 和索引?

Is there an owned version of Chars that does not need a lifetime parameter or do I have to keep a Vec<char> and an index myself?

推荐答案

std::vec::IntoIter 在某种意义上是每个迭代器的自有版本.

std::vec::IntoIter is an owned version of every iterator, in a sense.

use std::vec::IntoIter;

struct Chunks {
    remaining: IntoIter<char>,
}

impl Chunks {
    fn new(s: String) -> Self {
        Chunks {
            remaining: s.chars().collect::<Vec<_>>().into_iter(),
        }
    }
}

游乐场链接

缺点是额外的分配和空间开销,但我不知道您的具体情况的迭代器.

Downside is additional allocation and a space overhead, but I am not aware of the iterator for your specific case.

这篇关于是否有 String::chars 的自有版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆