是否拥有String :: chars的自有版本? [英] Is there an owned version of String::chars?
本文介绍了是否拥有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
不拥有它迭代的字符,它不能超过& str
或字符串
它是从...创建。
Chars
doesn't own the characters it iterates over and it can't outlive the &str
or String
it was created from.
是否拥有 Chars
的自有版本,不需要生命周期参数,或者我是否需要保留 Vec< char>
和我自己的索引?
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屋!
查看全文