gpt4 book ai didi

rust - Rust:如何限制Iterator::next()的生存期?

转载 作者:行者123 更新时间:2023-12-03 11:46:31 25 4
gpt4 key购买 nike

以下代码无法编译:

struct Things {
things: Vec<usize>
}

struct ThingsIterMut<'a> {
contents: &'a mut Vec<usize>,
indices: std::slice::Iter<'a, usize>
}

impl<'a> Iterator for ThingsIterMut<'a> {
type Item = &'a mut usize;

fn next(&mut self) -> Option<Self::Item> {
match self.indices.next() {
None => None,
Some(i) => self.contents.get_mut(*i)
}
}

}

impl Things {
pub fn iter_mut<'a>(&'a mut self) -> ThingsIterMut<'a> {
ThingsIterMut {
contents: &mut self.things,
indices: self.things.iter()
}

}
}

fn main() {
println!("Hello, world!");
}

它提示:
error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
--> src/main.rs:16:24
|
16 | Some(i) => self.contents.get_mut(*i)
| ^^^^^^^^^^^^^
|
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 13:5...
--> src/main.rs:13:5
|
13 | fn next(&mut self) -> Option<Self::Item> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: ...so that reference does not outlive borrowed content
--> src/main.rs:16:24
|
16 | Some(i) => self.contents.get_mut(*i)
| ^^^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime `'a` as defined on the impl at 10:6...
--> src/main.rs:10:6
|
10 | impl<'a> Iterator for ThingsIterMut<'a> {
| ^^
note: ...so that the types are compatible
--> src/main.rs:13:46
|
13 | fn next(&mut self) -> Option<Self::Item> {
| ______________________________________________^
14 | | match self.indices.next() {
15 | | None => None,
16 | | Some(i) => self.contents.get_mut(*i)
17 | | }
18 | | }
| |_____^
= note: expected `std::iter::Iterator`
found `std::iter::Iterator`
不能将 next更改为 next(&'a mut self)(签名不匹配),也不能将 self.contents.get_mut()更改为 self.contents.get_mut::<'a>()
解决此问题的正确方法是什么?

最佳答案

我看到两个问题。首先是您的iter_mut函数尝试返回对self.things的可变引用和不可变引用。
通过简化它,更容易理解为什么借用检查器不允许这样做:

fn main() {
let mut things = vec![1, 2, 3];
let contents = &mut things;
let indices = things.iter(); // borrows self_things immutably
let things_iter_mut = (contents, indices);
}
您试图返回比传递给 next函数更长的引用的第二个问题。
struct Things<'things> {
contents: &'things mut Vec<usize>,
}

impl<'things> Things<'things> {
// This won't compile! The 'borrow lifetime is implied.
// But here you can see that the borrow might be shorter than
// what we are returning.
fn next(&'borrow mut self) -> &'things mut Vec<usize> {
self.contents
}

// This will compile. Because the returned reference lives
// just as long as the argument.
fn next(&'things mut self) -> &'things mut Vec<usize> {
self.contents
}
}

关于rust - Rust:如何限制Iterator::next()的生存期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66328188/

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