This question already has answers here:
Can I write an Iterator that mutates itself and then yields a reference into itself?
(1个答案)
How do I write an iterator that returns references to itself?
(3个答案)
3年前关闭。
我正在尝试实现一个迭代器:
而且我收到了非常详细的错误消息,但是我不知道如何修复代码:
为什么
(1个答案)
How do I write an iterator that returns references to itself?
(3个答案)
3年前关闭。
我正在尝试实现一个迭代器:
struct MyIterator<'a> {
s1: &'a str,
s2: String,
idx: usize,
}
impl<'a> MyIterator<'a> {
fn new(s1: &str) -> MyIterator {
MyIterator {
s1: s1,
s2: "Rust".to_string(),
idx: 0,
}
}
}
impl<'a> Iterator for MyIterator<'a> {
type Item = &'a str;
fn next(&mut self) -> Option<Self::Item> {
self.idx += 1;
match self.idx {
1 => Some(self.s1),
2 => Some(&self.s2),
_ => None,
}
}
}
而且我收到了非常详细的错误消息,但是我不知道如何修复代码:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src\main.rs:39:23
|
39 | 2 => Some(&self.s2),
| ^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 34:5...
--> src\main.rs:34:5
|
34 | / fn next(&mut self) -> Option<Self::Item> {
35 | | self.idx + 1;
36 | |
37 | | match self.idx {
... |
41 | | }
42 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src\main.rs:39:23
|
39 | 2 => Some(&self.s2),
| ^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 31:1...
--> src\main.rs:31:1
|
31 | / impl<'a> Iterator for MyIterator<'a> {
32 | | type Item = &'a str;
33 | |
34 | | fn next(&mut self) -> Option<Self::Item> {
... |
42 | | }
43 | | }
| |_^
note: ...so that types are compatible (expected std::iter::Iterator, found std::iter::Iterator)
--> src\main.rs:34:46
|
34 | fn next(&mut self) -> Option<Self::Item> {
| ______________________________________________^
35 | | self.idx + 1;
36 | |
37 | | match self.idx {
... |
41 | | }
42 | | }
为什么
s2
生存期不只是'a
? 最佳答案
返回的值的类型为Option<&'a str>
,但是'a
不能使MyIterator<'a>
保持 Activity 状态,因此它可能超出范围,并且包含了s2: String
。因此,'a
根本无法使s2
保持 Activity 状态。 (它只能使s1
保持 Activity 状态,这样可以更轻松地查看是否已编写fn new(s1: &'a str) -> MyIterator<'a>
)
此外, Iterator
特质的设计方式是,您可以永不在Iterator
函数中返回对next
本身中存储的内容的引用。
相反,您可以创建一个存储该值的类型,并实现 IntoIterator
以对其进行引用(使用一个单独的迭代器类型,该类型包含对存储对象的引用)。
关于rust - 尝试实现借入一些数据并拥有其他数据的迭代器时发生编译错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47054316/
10-16 04:30