问题描述
我需要在由 Iterator
方法返回的结构中保存对 next
字段的引用。然而,编译器无法为借用表达式推断合适的生命周期。
这在 Rust 的当前版本中是否可行,我该怎么做?
use std::collections::HashMap;
struct CellDataRef<'a> {
value: &'a str,}
struct Row<'a> {
data_ref: &'a HashMap<String,CellDataRef<'a>>,}
struct TableIterator<'a> {
data: HashMap<String,}
impl<'a> Iterator for TableIterator<'a> {
type Item = Row<'a>;
fn next(&mut self) -> Option<Self::Item> {
Some(Row {
data_ref: &self.data,})
}
}
编译器错误:
error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
--> src/lib.rs:20:23
|
20 | data_ref: &self.data,| ^^^^^^^^^^
|
note: first,the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 18:5...
--> src/lib.rs:18:5
|
18 | fn next(&mut self) -> Option<Self::Item> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/lib.rs:20:23
|
20 | data_ref: &self.data,| ^^^^^^^^^^
note: but,the lifetime must be valid for the lifetime `'a` as defined on the impl at 15:6...
--> src/lib.rs:15:6
|
15 | impl<'a> Iterator for TableIterator<'a> {
| ^^
note: ...so that the types are compatible
--> src/lib.rs:18:46
|
18 | fn next(&mut self) -> Option<Self::Item> {
| ______________________________________________^
19 | | Some(Row {
20 | | data_ref: &self.data,21 | | })
22 | | }
| |_____^
= note: expected `Iterator`
found `Iterator`
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)