gpt4 book ai didi

rust - 在迭代器特征中指定关联类型的生命周期

转载 作者:行者123 更新时间:2023-12-01 05:51:30 24 4
gpt4 key购买 nike

我是 Rust 的新手,我想弄清楚在 Rust 中执行以下操作的最佳方法是什么:

struct ThingIterator {
current: String,
stop: String,
}

impl Iterator for ThingIterator {
type Item = &str;
fn next(&mut self) -> Option<&str> {
if self.current == self.stop {
return None;
}
// For testing
self.current = self.stop;
Some(&self.current)
}
}

fn main() {
let pi = ThingIterator {
current: String::from("Ask"),
stop: String::from("Zoo"),
};
println!("Number of things={}", pi.count());
}

我的错误是:

error[E0106]: missing lifetime specifier
--> src/main.rs:7:17
|
7 | type Item = &str;
| ^ expected lifetime parameter

error: aborting due to previous error

这是有道理的,我需要指定从 next() 返回的引用的有效期。我猜测函数本身很好,因为生命周期被省略了(不确定省略的共轭)——但我不知何故需要定义“type Item = &str”行的生命周期。

在我的例子中,只要“current”有效,即与“self”的生命周期相同,它就会有效。

我在 Rust 书籍或其他文档中没有看到任何内容可以帮助我解决这个问题。

附言抱歉,如果我在混淆术语,我对 Rust 非常陌生。谢谢

最佳答案

next&mut self 的生命周期不在定义类型 Item 的范围内,所以 Item 不能依赖那一生。相反,通常让 ThingIterator 保存引用而不是拥有的数据。如果仍然有一个拥有数据的结构,您可能会为 &OwnsData 实现 IntoIterator 以转换为使用引用的类型。

// ThingIterator is now generic in the lifetime 'a
// and it holds references rather than owned Strings.
struct ThingIterator<'a> {
current: &'a str,
stop: &'a str,
}

impl<'a> Iterator for ThingIterator<'a> {
// Now we can use the lifetime from ThingIterator here.
type Item = &'a str;
fn next(&mut self) -> Option<&'a str> {
if self.current == self.stop {
return None;
}
// For testing
self.current = self.stop;
Some(self.current)
}
}

// Typically, you'll have a type that owns its data
// Like Vec<T>, HashSet<T>, etc.
struct OwnsData {
current: String,
stop: String,
}

impl OwnsData {
// We'll have the traditional method that takes a reference
// to self and returns an iterator over references into self.

// Explicit lifetimes aren't needed, but it might help with understanding.
// fn iter<'a>(&'a self) -> ThingIterator<'a> {

fn iter(&self) -> ThingIterator {
ThingIterator {
current: &self.current,
stop: &self.stop,
}
}
}

// Then, we'll implement IntoIterator for references to OwnsData
// using the OwnsData::iter method defined above.
// This is helpful because for loops and many iterator methods
// use IntoIterator to work.
impl<'a> IntoIterator for &'a OwnsData {
// We'll be converting into ThingIterator
type IntoIter = ThingIterator<'a>;
type Item = &'a str;

fn into_iter(self) -> ThingIterator<'a> {
self.iter()
}
}

fn main() {
let pi = ThingIterator {
current: "Ask",
stop: "Zoo",
};
println!("Number of things={}", pi.count());

// Alternatively, we could start with Strings
// and use OwnsData
let tau = OwnsData {
current: "Ask".to_string(),
stop: "Zoo".to_string(),
};
println!("Number of things={}", tau.iter().count());
}

(playground)

另见

附言您要查找的词已被“删除”。

关于rust - 在迭代器特征中指定关联类型的生命周期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59518597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com