【发布时间】:2023-01-09 03:08:05
【问题描述】:
我有以下类型定义:
pub struct UTF8Chars {
bytes: Peekable<Box<dyn Iterator<Item = u8>>>,
}
现在我想知道如何实际创建这个结构的实例。
我试过了(是的,如果这是一个重要的细节,这是在特征实现中):
impl<'a> ToUTF8Chars for &'a str {
fn utf8_chars(self) -> UTF8Chars {
let bytes = Box::new(self.bytes()).peekable();
UTF8Chars { bytes }
}
}
这给了我错误:
expected struct `Peekable<Box<(dyn Iterator<Item = u8> + 'static)>>`
found struct `Peekable<Box<std::str::Bytes<'_>>>`
如果我尝试了奇怪的事情,请原谅我,但我还没有掌握这种复杂的特质。据我所知,rust-analyzer 告诉我 Bytes 实际上是 impl Iterator<Item = u8>。所以,接下来我尝试的是先投射它:
let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;
UTF8Chars { bytes: bytes.peekable() }
那种工作,但现在借用检查员抱怨:
impl<'a> ToUTF8Chars for &'a str {
-- lifetime `'a` defined here
fn utf8_chars(self) -> UTF8Chars {
let bytes = Box::new(self.bytes()) as Box<dyn Iterator<Item = u8>>;
^^^^^^^^^^^^^^^^^^^^^^ cast requires that `'a` must outlive `'static`
我不确定这里有什么超出范围...据我所知,我拥有来自 .bytes() 的结果(我也尝试使用额外的 .clone() 以防假设不正确),我拥有Box、Box传递给Peekable,最后Peekable传递给UTF8Chars。什么确切地是这里的问题吗?为什么我需要比static...活得更久?
我发现这个问题看起来很相似,遗憾的是没有答案:Peekable of an Iterator in struct。
我为什么要这样做?
好吧,主要是因为我不太关心,或者无法关心底层数据究竟是什么。我只需要知道我可以 .peek() 和 .next() 等等。这是因为有时我想将不同的东西分配给 self.bytes。例如,Chain<...> 或 Copied<...> 而不是简单的 vec::IntoIter<...>。
如果有替代方法,我很高兴听到它。
【问题讨论】:
标签: rust