Lifetime weird case
@dsal3389
·
2026-04-24
·
via The Rust Programming Language Forum - Latest posts
I have some weird case with lifetime, here is a small recreation of the code play.rust-lang.org Rust Playground A browser interface to the Rust compiler to experiment with the language struct Foo(Vec<i32>); impl Foo { fn iter(&self) -> impl Iterator<Item = &i32> { self.0.iter() } } fn main() { let mut x = Foo(vec![1, 2, 3, 4]); if let Some(v) = x.iter().nth(2).map(|i| i.to_string()) { x.0.push(5); } } I was under the impression that x.iter lifetime will not interfere with the if statement block after calling map , since the returned value from map is not a reference, but rust complains that x.0 is already borrowed as immutable this for example works let mut x = Foo(vec![1, 2, 3, 4]); let n = x.iter().nth(2).map(|i| i.to_string()); if let Some(v) = n { x.0.push(5); } even this let mut x = Foo(vec![1, 2, 3, 4]); if let Some(v) = x.0.iter().nth(2).map(|i| i.to_string()) { x.0.push(5); } I don't fully understand why the first example doesn't work...
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。