我试图返回新接收的值和缓存值之间所有组合的迭代器,但是我遇到了终身问题。
use std::collections::HashMap;
pub struct Status {
// <i,Vec<u>>
old: HashMap<usize, Vec<usize>>,
}
impl<'a> Status {
pub fn new() -> Self {
Status {
old: HashMap::new(),
}
}
pub fn gen(&mut self, u: usize, i: usize) -> UserPairIter<'a> {
let entry: &'a mut Vec<usize> = self.old.entry(i).or_insert(Vec::new());
UserPairIter::new(entry, u)
}
}
struct UserPairIter<'a> {
data: &'a mut Vec<usize>,
u: usize,
index: usize,
}
impl<'a> UserPairIter<'a> {
pub fn new(data: &'a mut Vec<usize>, u: usize) -> Self {
UserPairIter { data, u, index: 0 }
}
}
impl<'a> Iterator for UserPairIter<'a> {
type Item = (usize, usize);
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.data.len() {
self.data.push(self.u);
return None;
}
let result = (self.u, self.data[self.index]);
self.index += 1;
Some(result)
}
}
fn main() {}
编译时,我会收到以下错误消息:
error[E0495]: cannot infer an appropriate lifetime for autoref due to conflicting requirements
--> src/main.rs:16:50
|
16 | let entry: &'a mut Vec<usize> = self.old.entry(i).or_insert(Vec::new());
| ^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 15:5...
--> src/main.rs:15:5
|
15 | / pub fn gen(&mut self, u: usize, i: usize) -> UserPairIter<'a> {
16 | | let entry: &'a mut Vec<usize> = self.old.entry(i).or_insert(Vec::new());
17 | | UserPairIter::new(entry, u)
18 | | }
| |_____^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:16:41
|
16 | let entry: &'a mut Vec<usize> = self.old.entry(i).or_insert(Vec::new());
| ^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 8:1...
--> src/main.rs:8:1
|
8 | / impl<'a> Status {
9 | | pub fn new() -> Self {
10 | | Status {
11 | | old: HashMap::new(),
... |
18 | | }
19 | | }
| |_^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:16:41
|
16 | let entry: &'a mut Vec<usize> = self.old.entry(i).or_insert(Vec::new());
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
首先,请勿将Lifetime Generic放入Status
中。如果您需要在函数中进行通用,请将此参数放在函数中:
impl Status {
pub fn new() -> Self {
Status {
old: HashMap::new(),
}
}
pub fn gen<'a>(&mut self, u: usize, i: usize) -> UserPairIter<'a> {
let entry: &'a mut Vec<usize> = self.old.entry(i).or_insert(Vec::new());
UserPairIter::new(entry, u)
}
}
然后,编译器说它不能推断self.old
的寿命。只需用&'a mut self
提供提示,以便编译器了解UserPairIter
的寿命与Status
的寿命相同:
impl Status {
pub fn new() -> Self {
Status {
old: HashMap::new(),
}
}
pub fn gen<'a>(&'a mut self, u: usize, i: usize) -> UserPairIter<'a> {
let entry: &'a mut Vec<usize> = self.old.entry(i).or_insert(Vec::new());
UserPairIter::new(entry, u)
}
}
那没关系!
您不需要说entry
的类型,编译器可以通过功能签名来推断它:
pub fn gen<'a>(&'a mut self, u: usize, i: usize) -> UserPairIter<'a> {
let entry = self.old.entry(i).or_insert(Vec::new());
UserPairIter::new(entry, u)
}